diff --git a/.github/workflows/ci-scripts.yml b/.github/workflows/ci-scripts.yml index c8c4d0998..5f0cc7511 100644 --- a/.github/workflows/ci-scripts.yml +++ b/.github/workflows/ci-scripts.yml @@ -12,6 +12,7 @@ on: - ci/extract_sdk_doc_links.py - ci/build_cli_linux.sh - ci/package_cli.py + - ci/update_homebrew_formula.py - .bumpversion.toml - rust/lancedb/cli/Cargo.toml - ci/set_lance_version.py @@ -26,6 +27,7 @@ on: - ci/extract_sdk_doc_links.py - ci/build_cli_linux.sh - ci/package_cli.py + - ci/update_homebrew_formula.py - .bumpversion.toml - rust/lancedb/cli/Cargo.toml - ci/set_lance_version.py diff --git a/.github/workflows/gh-release.yml b/.github/workflows/gh-release.yml index eedf8450c..5961f444c 100644 --- a/.github/workflows/gh-release.yml +++ b/.github/workflows/gh-release.yml @@ -19,6 +19,8 @@ jobs: gh-release: needs: cli runs-on: ubuntu-latest + outputs: + prerelease: ${{ steps.extract_version.outputs.prerelease }} permissions: contents: write steps: @@ -102,9 +104,58 @@ jobs: fail_on_unmatched_files: true overwrite_files: true + homebrew: + name: Open Homebrew formula PR + needs: gh-release + if: github.repository == 'lancedb/lancedb' && needs.gh-release.outputs.prerelease == 'false' + runs-on: ubuntu-24.04 + environment: homebrew-tap + concurrency: homebrew-tap-${{ github.ref_name }} + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + repository: lancedb/homebrew-tap + ref: main + path: tap + persist-credentials: false + - name: Update formula from the published checksums + env: + GH_TOKEN: ${{ github.token }} + run: | + gh release download "$GITHUB_REF_NAME" --repo "$GITHUB_REPOSITORY" \ + --pattern SHA256SUMS --dir "$RUNNER_TEMP" + python3 -m ci.update_homebrew_formula "$GITHUB_REF_NAME" \ + "$RUNNER_TEMP/SHA256SUMS" tap/Formula/lancedb.rb + - name: Create tap installation token + id: app + uses: actions/create-github-app-token@f418cff399f7aef4c2f0ad47e25ca7a6abbdd6fc # v3.4.0 + with: + client-id: ${{ vars.HOMEBREW_TAP_APP_CLIENT_ID }} + private-key: ${{ secrets.HOMEBREW_TAP_APP_PRIVATE_KEY }} + owner: lancedb + repositories: homebrew-tap + permission-contents: write + permission-pull-requests: write + - name: Open or update the tap PR + uses: peter-evans/create-pull-request@3ffccacd46053766916f087ce41d627c0b8cf2d1 # v8.1.3 + with: + path: tap + token: ${{ steps.app.outputs.token }} + base: main + branch: release/lancedb-${{ github.ref_name }} + add-paths: Formula/lancedb.rb + commit-message: Update LanceDB CLI to ${{ github.ref_name }} + title: Update LanceDB CLI to ${{ github.ref_name }} + body: | + Update the formula to [${{ github.ref_name }}](https://github.com/lancedb/lancedb/releases/tag/${{ github.ref_name }}) using its published SHA256SUMS. + Review and merge after the tap's install tests pass. + report-failure: runs-on: ubuntu-24.04 - needs: [cli, gh-release] + needs: [cli, gh-release, homebrew] if: always() && failure() permissions: contents: read diff --git a/Cargo.lock b/Cargo.lock index 9822a132a..bc9dbc012 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3885,8 +3885,8 @@ checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" [[package]] name = "fsst" -version = "15.0.0-beta.32" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.32#1115237a5eca8372494ef2d9c6d7886455cb51a6" +version = "15.0.0-beta.34" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.34#abf5c3334780ad007f63b7402655cd1c311c6beb" dependencies = [ "arrow-array", "rand 0.9.5", @@ -5364,8 +5364,8 @@ checksum = "e037a2e1d8d5fdbd49b16a4ea09d5d6401c1f29eca5ff29d03d3824dba16256a" [[package]] name = "lance" -version = "15.0.0-beta.32" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.32#1115237a5eca8372494ef2d9c6d7886455cb51a6" +version = "15.0.0-beta.34" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.34#abf5c3334780ad007f63b7402655cd1c311c6beb" dependencies = [ "arc-swap", "arrow", @@ -5413,6 +5413,7 @@ dependencies = [ "lance-namespace", "lance-select", "lance-table", + "lance-table-runtime", "lance-tokenizer", "log", "moka", @@ -5440,8 +5441,8 @@ dependencies = [ [[package]] name = "lance-arrow" -version = "15.0.0-beta.32" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.32#1115237a5eca8372494ef2d9c6d7886455cb51a6" +version = "15.0.0-beta.34" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.34#abf5c3334780ad007f63b7402655cd1c311c6beb" dependencies = [ "arrow-array", "arrow-buffer", @@ -5464,8 +5465,8 @@ dependencies = [ [[package]] name = "lance-bitpacking" -version = "15.0.0-beta.32" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.32#1115237a5eca8372494ef2d9c6d7886455cb51a6" +version = "15.0.0-beta.34" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.34#abf5c3334780ad007f63b7402655cd1c311c6beb" dependencies = [ "arrayref", "crunchy", @@ -5475,8 +5476,8 @@ dependencies = [ [[package]] name = "lance-core" -version = "15.0.0-beta.32" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.32#1115237a5eca8372494ef2d9c6d7886455cb51a6" +version = "15.0.0-beta.34" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.34#abf5c3334780ad007f63b7402655cd1c311c6beb" dependencies = [ "arrow-array", "arrow-buffer", @@ -5514,8 +5515,8 @@ dependencies = [ [[package]] name = "lance-datafusion" -version = "15.0.0-beta.32" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.32#1115237a5eca8372494ef2d9c6d7886455cb51a6" +version = "15.0.0-beta.34" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.34#abf5c3334780ad007f63b7402655cd1c311c6beb" dependencies = [ "arrow", "arrow-array", @@ -5546,8 +5547,8 @@ dependencies = [ [[package]] name = "lance-datafusion-exec" -version = "15.0.0-beta.32" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.32#1115237a5eca8372494ef2d9c6d7886455cb51a6" +version = "15.0.0-beta.34" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.34#abf5c3334780ad007f63b7402655cd1c311c6beb" dependencies = [ "arrow", "arrow-array", @@ -5563,6 +5564,7 @@ dependencies = [ "half", "lance-arrow", "lance-core", + "lance-io", "lance-jsonb", "log", "pin-project", @@ -5572,8 +5574,8 @@ dependencies = [ [[package]] name = "lance-datagen" -version = "15.0.0-beta.32" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.32#1115237a5eca8372494ef2d9c6d7886455cb51a6" +version = "15.0.0-beta.34" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.34#abf5c3334780ad007f63b7402655cd1c311c6beb" dependencies = [ "arrow", "arrow-array", @@ -5590,8 +5592,8 @@ dependencies = [ [[package]] name = "lance-derive" -version = "15.0.0-beta.32" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.32#1115237a5eca8372494ef2d9c6d7886455cb51a6" +version = "15.0.0-beta.34" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.34#abf5c3334780ad007f63b7402655cd1c311c6beb" dependencies = [ "proc-macro2", "quote", @@ -5600,8 +5602,8 @@ dependencies = [ [[package]] name = "lance-encoding" -version = "15.0.0-beta.32" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.32#1115237a5eca8372494ef2d9c6d7886455cb51a6" +version = "15.0.0-beta.34" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.34#abf5c3334780ad007f63b7402655cd1c311c6beb" dependencies = [ "arrow-arith", "arrow-array", @@ -5635,8 +5637,8 @@ dependencies = [ [[package]] name = "lance-file" -version = "15.0.0-beta.32" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.32#1115237a5eca8372494ef2d9c6d7886455cb51a6" +version = "15.0.0-beta.34" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.34#abf5c3334780ad007f63b7402655cd1c311c6beb" dependencies = [ "arrow-arith", "arrow-array", @@ -5649,7 +5651,6 @@ dependencies = [ "async-trait", "byteorder", "bytes", - "datafusion-common", "futures", "lance-arrow", "lance-core", @@ -5667,8 +5668,8 @@ dependencies = [ [[package]] name = "lance-geo" -version = "15.0.0-beta.32" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.32#1115237a5eca8372494ef2d9c6d7886455cb51a6" +version = "15.0.0-beta.34" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.34#abf5c3334780ad007f63b7402655cd1c311c6beb" dependencies = [ "arrow-array", "arrow-schema", @@ -5699,8 +5700,8 @@ dependencies = [ [[package]] name = "lance-index" -version = "15.0.0-beta.32" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.32#1115237a5eca8372494ef2d9c6d7886455cb51a6" +version = "15.0.0-beta.34" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.34#abf5c3334780ad007f63b7402655cd1c311c6beb" dependencies = [ "arc-swap", "arrow", @@ -5772,8 +5773,8 @@ dependencies = [ [[package]] name = "lance-index-core" -version = "15.0.0-beta.32" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.32#1115237a5eca8372494ef2d9c6d7886455cb51a6" +version = "15.0.0-beta.34" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.34#abf5c3334780ad007f63b7402655cd1c311c6beb" dependencies = [ "arrow-array", "arrow-schema", @@ -5796,8 +5797,8 @@ dependencies = [ [[package]] name = "lance-io" -version = "15.0.0-beta.32" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.32#1115237a5eca8372494ef2d9c6d7886455cb51a6" +version = "15.0.0-beta.34" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.34#abf5c3334780ad007f63b7402655cd1c311c6beb" dependencies = [ "arrow", "arrow-array", @@ -5842,8 +5843,8 @@ dependencies = [ [[package]] name = "lance-jsonb" -version = "15.0.0-beta.32" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.32#1115237a5eca8372494ef2d9c6d7886455cb51a6" +version = "15.0.0-beta.34" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.34#abf5c3334780ad007f63b7402655cd1c311c6beb" dependencies = [ "byteorder", "ethnum", @@ -5860,7 +5861,7 @@ dependencies = [ [[package]] name = "lance-linalg" -version = "15.0.0-beta.32" +version = "15.0.0-beta.34" dependencies = [ "approx", "argminmax 0.7.1", @@ -5882,8 +5883,8 @@ dependencies = [ [[package]] name = "lance-namespace" -version = "15.0.0-beta.32" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.32#1115237a5eca8372494ef2d9c6d7886455cb51a6" +version = "15.0.0-beta.34" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.34#abf5c3334780ad007f63b7402655cd1c311c6beb" dependencies = [ "arrow", "async-trait", @@ -5897,8 +5898,8 @@ dependencies = [ [[package]] name = "lance-namespace-impls" -version = "15.0.0-beta.32" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.32#1115237a5eca8372494ef2d9c6d7886455cb51a6" +version = "15.0.0-beta.34" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.34#abf5c3334780ad007f63b7402655cd1c311c6beb" dependencies = [ "arc-swap", "arrow", @@ -5952,8 +5953,8 @@ dependencies = [ [[package]] name = "lance-select" -version = "15.0.0-beta.32" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.32#1115237a5eca8372494ef2d9c6d7886455cb51a6" +version = "15.0.0-beta.34" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.34#abf5c3334780ad007f63b7402655cd1c311c6beb" dependencies = [ "arrow-array", "arrow-buffer", @@ -5967,8 +5968,8 @@ dependencies = [ [[package]] name = "lance-table" -version = "15.0.0-beta.32" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.32#1115237a5eca8372494ef2d9c6d7886455cb51a6" +version = "15.0.0-beta.34" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.34#abf5c3334780ad007f63b7402655cd1c311c6beb" dependencies = [ "arrow", "arrow-array", @@ -6007,10 +6008,55 @@ dependencies = [ "uuid", ] +[[package]] +name = "lance-table-runtime" +version = "15.0.0-beta.34" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.34#abf5c3334780ad007f63b7402655cd1c311c6beb" +dependencies = [ + "arrow-array", + "arrow-buffer", + "arrow-cast", + "arrow-data", + "arrow-ipc", + "arrow-row", + "arrow-schema", + "arrow-select", + "async-trait", + "blake3", + "byteorder", + "bytes", + "chrono", + "futures", + "humantime", + "itertools 0.14.0", + "lance-arrow", + "lance-core", + "lance-encoding", + "lance-file", + "lance-io", + "lance-namespace", + "lance-select", + "lance-table", + "log", + "object_store 0.14.2", + "prost", + "prost-types", + "rand 0.9.5", + "roaring", + "semver", + "serde", + "serde_json", + "snafu 0.9.0", + "tokio", + "tracing", + "url", + "uuid", +] + [[package]] name = "lance-testing" -version = "15.0.0-beta.32" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.32#1115237a5eca8372494ef2d9c6d7886455cb51a6" +version = "15.0.0-beta.34" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.34#abf5c3334780ad007f63b7402655cd1c311c6beb" dependencies = [ "arrow-array", "arrow-schema", @@ -6023,8 +6069,8 @@ dependencies = [ [[package]] name = "lance-tokenizer" -version = "15.0.0-beta.32" -source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.32#1115237a5eca8372494ef2d9c6d7886455cb51a6" +version = "15.0.0-beta.34" +source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.34#abf5c3334780ad007f63b7402655cd1c311c6beb" dependencies = [ "frostem", "icu_segmenter", diff --git a/Cargo.toml b/Cargo.toml index 0589ee95a..5b5011807 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -20,20 +20,20 @@ categories = ["database-implementations"] rust-version = "1.95.0" [workspace.dependencies] -lance = { "version" = "=15.0.0-beta.32", default-features = false, "tag" = "v15.0.0-beta.32", "git" = "https://github.com/lance-format/lance.git" } -lance-core = { "version" = "=15.0.0-beta.32", "tag" = "v15.0.0-beta.32", "git" = "https://github.com/lance-format/lance.git" } -lance-datagen = { "version" = "=15.0.0-beta.32", "tag" = "v15.0.0-beta.32", "git" = "https://github.com/lance-format/lance.git" } -lance-file = { "version" = "=15.0.0-beta.32", "tag" = "v15.0.0-beta.32", "git" = "https://github.com/lance-format/lance.git" } -lance-io = { "version" = "=15.0.0-beta.32", default-features = false, "tag" = "v15.0.0-beta.32", "git" = "https://github.com/lance-format/lance.git" } -lance-index = { "version" = "=15.0.0-beta.32", "tag" = "v15.0.0-beta.32", "git" = "https://github.com/lance-format/lance.git" } -lance-jsonb = { "version" = "=15.0.0-beta.32", "tag" = "v15.0.0-beta.32", "git" = "https://github.com/lance-format/lance.git" } -lance-namespace = { "version" = "=15.0.0-beta.32", "tag" = "v15.0.0-beta.32", "git" = "https://github.com/lance-format/lance.git" } -lance-namespace-impls = { "version" = "=15.0.0-beta.32", default-features = false, "tag" = "v15.0.0-beta.32", "git" = "https://github.com/lance-format/lance.git" } -lance-table = { "version" = "=15.0.0-beta.32", "tag" = "v15.0.0-beta.32", "git" = "https://github.com/lance-format/lance.git" } -lance-testing = { "version" = "=15.0.0-beta.32", "tag" = "v15.0.0-beta.32", "git" = "https://github.com/lance-format/lance.git" } -lance-datafusion = { "version" = "=15.0.0-beta.32", "tag" = "v15.0.0-beta.32", "git" = "https://github.com/lance-format/lance.git" } -lance-encoding = { "version" = "=15.0.0-beta.32", "tag" = "v15.0.0-beta.32", "git" = "https://github.com/lance-format/lance.git" } -lance-arrow = { "version" = "=15.0.0-beta.32", "tag" = "v15.0.0-beta.32", "git" = "https://github.com/lance-format/lance.git" } +lance = { "version" = "=15.0.0-beta.34", default-features = false, "tag" = "v15.0.0-beta.34", "git" = "https://github.com/lance-format/lance.git" } +lance-core = { "version" = "=15.0.0-beta.34", "tag" = "v15.0.0-beta.34", "git" = "https://github.com/lance-format/lance.git" } +lance-datagen = { "version" = "=15.0.0-beta.34", "tag" = "v15.0.0-beta.34", "git" = "https://github.com/lance-format/lance.git" } +lance-file = { "version" = "=15.0.0-beta.34", "tag" = "v15.0.0-beta.34", "git" = "https://github.com/lance-format/lance.git" } +lance-io = { "version" = "=15.0.0-beta.34", default-features = false, "tag" = "v15.0.0-beta.34", "git" = "https://github.com/lance-format/lance.git" } +lance-index = { "version" = "=15.0.0-beta.34", "tag" = "v15.0.0-beta.34", "git" = "https://github.com/lance-format/lance.git" } +lance-jsonb = { "version" = "=15.0.0-beta.34", "tag" = "v15.0.0-beta.34", "git" = "https://github.com/lance-format/lance.git" } +lance-namespace = { "version" = "=15.0.0-beta.34", "tag" = "v15.0.0-beta.34", "git" = "https://github.com/lance-format/lance.git" } +lance-namespace-impls = { "version" = "=15.0.0-beta.34", default-features = false, "tag" = "v15.0.0-beta.34", "git" = "https://github.com/lance-format/lance.git" } +lance-table = { "version" = "=15.0.0-beta.34", "tag" = "v15.0.0-beta.34", "git" = "https://github.com/lance-format/lance.git" } +lance-testing = { "version" = "=15.0.0-beta.34", "tag" = "v15.0.0-beta.34", "git" = "https://github.com/lance-format/lance.git" } +lance-datafusion = { "version" = "=15.0.0-beta.34", "tag" = "v15.0.0-beta.34", "git" = "https://github.com/lance-format/lance.git" } +lance-encoding = { "version" = "=15.0.0-beta.34", "tag" = "v15.0.0-beta.34", "git" = "https://github.com/lance-format/lance.git" } +lance-arrow = { "version" = "=15.0.0-beta.34", "tag" = "v15.0.0-beta.34", "git" = "https://github.com/lance-format/lance.git" } lancedb = { path = "rust/lancedb", default-features = false } ahash = "0.8" anyhow = "1" diff --git a/ci/tests/test_update_homebrew_formula.py b/ci/tests/test_update_homebrew_formula.py new file mode 100644 index 000000000..4996ddadd --- /dev/null +++ b/ci/tests/test_update_homebrew_formula.py @@ -0,0 +1,52 @@ +import unittest + +from ci.update_homebrew_formula import update_formula + + +class HomebrewFormulaTest(unittest.TestCase): + targets = [ + "aarch64-apple-darwin", + "x86_64-unknown-linux-gnu", + "aarch64-unknown-linux-gnu", + ] + tag = "v0.42.10" + + def setUp(self): + self.formula = ' version "0.42.10-beta.26"\n' + self.manifest = "" + for index, target in enumerate(self.targets, start=1): + self.formula += f' url "#{{archive}}-{target}.tar.gz"\n' + self.formula += f' sha256 "{"0" * 64}"\n' + entry = f"{str(index) * 64} lancedb-{self.tag}-{target}.tar.gz\n" + self.manifest = entry + self.manifest + self.formula += ' desc "Command-line client for LanceDB"\n' + + def test_updates_each_platform_and_preserves_rest_of_formula(self): + result = update_formula(self.formula, self.tag, self.manifest) + expected = self.formula.replace("0.42.10-beta.26", "0.42.10") + for index in range(1, 4): + expected = expected.replace("0" * 64, str(index) * 64, 1) + self.assertEqual(result, expected) + self.assertEqual(update_formula(result, self.tag, self.manifest), result) + + def test_retry_of_older_release_cannot_downgrade_the_tap(self): + formula = self.formula.replace("0.42.10-beta.26", "0.43.0") + self.assertEqual(update_formula(formula, self.tag, self.manifest), formula) + + def test_rejects_prereleases_and_incomplete_or_ambiguous_inputs(self): + with self.assertRaisesRegex(ValueError, "stable CLI release tag"): + update_formula(self.formula, "v0.42.10-beta.26", self.manifest) + for manifest in ( + self.manifest.split("\n", 1)[1], + self.manifest + self.manifest, + self.manifest.replace("v0.42.10", "v0.42.9"), + self.manifest.replace("1" * 64, "invalid"), + ): + with self.subTest(manifest=manifest), self.assertRaises(ValueError): + update_formula(self.formula, self.tag, manifest) + for formula in ( + self.formula.replace("aarch64-apple-darwin", "unexpected-target"), + self.formula + self.formula, + ): + with self.subTest(formula=formula), self.assertRaises(ValueError): + update_formula(formula, self.tag, self.manifest) diff --git a/ci/update_homebrew_formula.py b/ci/update_homebrew_formula.py new file mode 100644 index 000000000..554adb22d --- /dev/null +++ b/ci/update_homebrew_formula.py @@ -0,0 +1,65 @@ +"""Update the tap formula from a stable CLI release's SHA256SUMS.""" + +import argparse +from pathlib import Path +import re + +from ci.package_cli import TARGETS, archive_stem + + +def update_formula(formula: str, tag: str, manifest: str) -> str: + stable_version = r"[0-9]+\.[0-9]+\.[0-9]+" + if not re.fullmatch(f"v{stable_version}", tag): + raise ValueError(f"Expected a stable CLI release tag, got {tag!r}") + version = tag[1:] + + version_line = rf'^ version "({stable_version})(?:-beta\.[0-9]+)?"$' + current = re.findall(version_line, formula, re.MULTILINE) + if len(current) != 1: + raise ValueError("Expected one CLI version declaration in the tap formula") + if tuple(map(int, current[0].split("."))) > tuple(map(int, version.split("."))): + # A maintainer may be retrying an older release after a newer tap PR merged. + return formula + + archives = {} + for line in manifest.splitlines(): + entry = re.fullmatch(r"([0-9a-f]{64}) (\S+)", line) + if not entry or entry[2] in archives: + raise ValueError(f"Invalid or duplicate entry in SHA256SUMS: {line!r}") + archives[entry[2]] = entry[1] + + filenames = {t: f"{archive_stem(version, t)}.tar.gz" for t in TARGETS} + if archives.keys() != set(filenames.values()): + raise ValueError(f"Expected SHA256SUMS for exactly the CLI archives for {tag}") + + updated = re.sub( + version_line, f' version "{version}"', formula, flags=re.MULTILINE + ) + for target, filename in filenames.items(): + # Match the URL and its following checksum together; platform order can change. + url = re.escape(f'url "#{{archive}}-{target}.tar.gz"') + pattern = rf'^([ \t]+{url}\n[ \t]+sha256 ")[0-9a-f]{{64}}"$' + updated, count = re.subn( + pattern, rf'\g<1>{archives[filename]}"', updated, flags=re.MULTILINE + ) + if count != 1: + raise ValueError( + f"Expected one URL and checksum for {target} in the formula" + ) + return updated + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("tag") + parser.add_argument("checksums", type=Path) + parser.add_argument("formula", type=Path) + args = parser.parse_args() + original = args.formula.read_text() + updated = update_formula(original, args.tag, args.checksums.read_text()) + if updated != original: + args.formula.write_text(updated) + + +if __name__ == "__main__": + main() diff --git a/docs/mkdocs.yml b/docs/mkdocs.yml index ad6fc4b65..b2bd4738a 100644 --- a/docs/mkdocs.yml +++ b/docs/mkdocs.yml @@ -72,11 +72,11 @@ plugins: separate_signature: true filters: - "!^_" - import: + inventories: # for cross references - https://arrow.apache.org/docs/objects.inv - https://pandas.pydata.org/docs/objects.inv - - https://docs.pydantic.dev/latest/objects.inv + - https://pydantic.dev/docs/validation/latest/objects.inv - render_swagger: allow_arbitrary_locations: true # - redirects: diff --git a/docs/requirements.txt b/docs/requirements.txt index 89de1cb71..3405e8dce 100644 --- a/docs/requirements.txt +++ b/docs/requirements.txt @@ -1,9 +1,9 @@ mkdocs==1.6.1 mkdocs-jupyter==0.24.1 -mkdocs-material==9.6.23 -mkdocs-autorefs>=0.5,<=1.0 -mkdocstrings[python]>=0.24,<1.0 -griffe>=0.40,<1.0 +mkdocs-material==9.8.2 +mkdocs-autorefs>=1.4 +mkdocstrings[python]>=1.0.7,<2 +pymdown-extensions>=11.0.1 mkdocs-render-swagger-plugin>=0.1.0 pydantic>=2.7.4,<3 mkdocs-redirects>=1.2.0 diff --git a/docs/src/js/classes/Index.md b/docs/src/js/classes/Index.md index b3fcf5ec3..d76acaa3c 100644 --- a/docs/src/js/classes/Index.md +++ b/docs/src/js/classes/Index.md @@ -261,6 +261,49 @@ using an underlying bitmap index. *** +### plugin() + +```ts +static plugin(indexType, params?): Index +``` + +Create a scalar index of a type recognized by a registered database plugin. + +Use this for index types without a dedicated factory on `Index`. +Prefer a dedicated factory when one is available. + +An unknown plugin name or invalid parameters cause `createIndex` to fail. + +#### Parameters + +* **indexType**: `string` + The index type, case-insensitive. + Surrounding whitespace is ignored. Must not be empty. + +* **params?**: `string` \| `Record`<`string`, `unknown`> + The index parameters, as an object or as a string + holding a JSON object. They are passed as given. Each plugin defines + its parameters and defaults; refer to the plugin's documentation + for guidance. + +#### Returns + +[`Index`](Index.md) + +#### Throws + +If `indexType` is empty, or `params` is not a JSON object. + +#### Example + +```ts +await table.createIndex("id", { + config: Index.plugin("bloomfilter", { number_of_items: 4096 }), +}); +``` + +*** + ### rtree() ```ts diff --git a/docs/web-tests/py/test_quickstart.py b/docs/web-tests/py/test_quickstart.py index ac8396db0..60d8852ec 100644 --- a/docs/web-tests/py/test_quickstart.py +++ b/docs/web-tests/py/test_quickstart.py @@ -344,10 +344,11 @@ def flatten_stats(table): # --8<-- [end:quickstart_flatten_stats] -def test_quickstart_derived_feature(db_path_factory): - db = lancedb.connect(db_path_factory("derived_feature")) - table = create_frames(db) +def test_quickstart_derived_feature_on_a_deployment(deployment): + # Functions need LanceDB Enterprise: LanceDB Embedded has no Function catalog. + table = create_frames(deployment) flatten_stats(table) + db = deployment.db # --8<-- [start:quickstart_add_feature] from lancedb import col, function @@ -369,7 +370,8 @@ def test_quickstart_derived_feature(db_path_factory): ) } ) - table.refresh_column("quality_score") + job = table.refresh_column_async("quality_score") + job.wait() # --8<-- [end:quickstart_add_feature] # --8<-- [start:quickstart_query_feature] @@ -379,38 +381,8 @@ def test_quickstart_derived_feature(db_path_factory): print(features) # --8<-- [end:quickstart_query_feature] assert quality_scores(table) == EXPECTED_QUALITY_SCORES - - -def test_quickstart_derived_feature_on_a_deployment(deployment): - table = create_frames(deployment) - flatten_stats(table) - - from lancedb import col, function - - @function - def quality_score( - motion: float, sharpness: float, exposure: float, framing: float - ) -> float: - return (motion + sharpness + exposure + framing) / 4.0 - - version = deployment.db.create_function_async(quality_score).wait() - table.add_columns( - { - "quality_score": version( - motion=col("motion"), - sharpness=col("sharpness"), - exposure=col("exposure"), - framing=col("framing"), - ) - } - ) - - # --8<-- [start:quickstart_add_feature_enterprise] - job = table.refresh_column_async("quality_score") - job.wait() - # --8<-- [end:quickstart_add_feature_enterprise] - assert quality_scores(table) == EXPECTED_QUALITY_SCORES - with pytest.raises(Exception): + # The blocking form raises on Enterprise, which is why the snippet uses a job. + with pytest.raises(NotImplementedError, match="refresh_column_async"): table.refresh_column("quality_score") diff --git a/docs/web/curation/create-function.mdx b/docs/web/curation/create-function.mdx index 01669901c..c898a40ae 100644 --- a/docs/web/curation/create-function.mdx +++ b/docs/web/curation/create-function.mdx @@ -553,11 +553,12 @@ def embed(text: str) -> list[float]: ... version = db.create_function(embed) table.add_columns( {"embedding": version(text=col("text"))}, - gpu_class="any", - gpu_count=1, total_gpu_count=8, ) -table.refresh_column("embedding", gpu_class="h100", gpu_count=4, total_gpu_count=8) +job = table.refresh_column_async( + "embedding", gpu_class="h100", total_gpu_count=8 +) +job.wait() db.create_materialized_view( "embeddings", query="SELECT embed(text) AS embedding FROM documents", @@ -570,7 +571,10 @@ db.create_materialized_view( `gpu_class` selects the GPU pool and `gpu_count` selects the positive number of devices allocated together to each worker. Both can be overridden at -column/MV creation and refresh. An explicit `gpu_class="any"` replaces a +column/MV creation and refresh. On LanceDB Enterprise, the Python +`add_columns` does not yet accept `gpu_class` or `gpu_count`, and +`refresh_column_async` does not yet accept `gpu_count`; those values come from +the registered Function. An explicit `gpu_class="any"` replaces a registered class with any eligible configured pool. These settings require a GPU Function for computed columns. The `total_*` values are ceilings for the whole worker fleet. CPU and memory can limit the fleet before it reaches its GPU ceiling. diff --git a/docs/web/curation/vend-secret.mdx b/docs/web/curation/vend-secret.mdx index 7d272c265..d78447154 100644 --- a/docs/web/curation/vend-secret.mdx +++ b/docs/web/curation/vend-secret.mdx @@ -106,7 +106,8 @@ table.add_columns( ) } ) -table.refresh_column("embedding") +job = table.refresh_column_async("embedding") +job.wait() ``` A decorated class calls `__init__` once per remote instance and `__call__` @@ -135,7 +136,7 @@ cached in the Function's definition: | Step | What happens | | --- | --- | | `add_columns` with this Function version | Every bound Secret must now exist. The column pins this exact version, not a value. | -| A refresh starts -- `refresh_column`, or a materialized view's refresh | Every bound Secret must still exist, checked before any row is computed. | +| A refresh starts: `refresh_column_async`, or a materialized view's refresh | Every bound Secret must still exist, checked before any row is computed. | | The job captures each bound Secret's current value | LanceDB looks up the value once, when the job starts, and sets it as that environment variable for every row the job evaluates, including its retries. No other environment variable carries over. | This is why rotating a Secret needs no new Function version and no column diff --git a/docs/web/enterprise/auto-refresh.mdx b/docs/web/enterprise/auto-refresh.mdx index 452d543e8..f9f313c56 100644 --- a/docs/web/enterprise/auto-refresh.mdx +++ b/docs/web/enterprise/auto-refresh.mdx @@ -11,7 +11,7 @@ availability: Both a [computed column](/feature-engineering/add-computed-column) and a [materialized view](/feature-engineering/materialized-views) can refresh themselves on a schedule instead of waiting for an explicit -`refresh_column()`, `view.refresh()`, or `REFRESH` statement. Either way, +`refresh_column_async()`, `view.refresh()`, or `REFRESH` statement. Either way, `auto_refresh_enabled` turns it on and `auto_refresh_interval_seconds` sets a minimum delay before the next automatic refresh is eligible -- omit the interval to let the server decide. What that delay is measured from differs diff --git a/docs/web/feature-engineering/add-computed-column.mdx b/docs/web/feature-engineering/add-computed-column.mdx index 730d0081e..76e5e03f1 100644 --- a/docs/web/feature-engineering/add-computed-column.mdx +++ b/docs/web/feature-engineering/add-computed-column.mdx @@ -183,7 +183,7 @@ large enough that you would rather control when the work happens. Automatic refresh is on by default for each computed column, and takes effect when your Enterprise deployment enables its refresh scheduler. Until then, -call [`refresh_column`](/feature-engineering/refresh-column) yourself. Pass +call [`refresh_column_async`](/feature-engineering/refresh-column#async) yourself. Pass `auto_refresh_enabled=False` to opt a column out, or `auto_refresh_interval_seconds` to set how often it refreshes: diff --git a/docs/web/indexing/scalar-index.mdx b/docs/web/indexing/scalar-index.mdx index a3bf06957..a28b33585 100644 --- a/docs/web/indexing/scalar-index.mdx +++ b/docs/web/indexing/scalar-index.mdx @@ -362,6 +362,51 @@ server can build the index and evaluate `ST_*` functions depends on its version. +## Create a plugin index by name + +LanceDB can create a scalar index of any type recognized by a registered database +plugin. For index types without a dedicated configuration, pass the type name and +optional parameters using `ScalarPlugin` in Python, `Index.plugin()` in TypeScript, +or `Index::Plugin(PluginIndexBuilder)` in Rust. Prefer a dedicated configuration, +such as `BTree`, when one is available. + +Index type names are case-insensitive. Surrounding whitespace is ignored. +Parameters are a JSON object and are passed as given. Each plugin defines its +parameters and defaults; refer to the plugin's documentation for guidance. +Python and TypeScript also accept parameters as a string holding a JSON object. + + +```python Python icon="python" +from lancedb.index import ScalarPlugin + +await tbl.create_index( + "id", config=ScalarPlugin("bloomfilter", {"number_of_items": 4096}) +) +``` + +```typescript TypeScript icon="square-js" +import { Index } from "@lancedb/lancedb"; + +await tbl.createIndex("id", { + config: Index.plugin("bloomfilter", { number_of_items: 4096 }), +}); +``` + +```rust Rust icon="rust" +use lancedb::index::Index; +use lancedb::index::scalar::PluginIndexBuilder; +use serde_json::json; + +let bloom_filter = PluginIndexBuilder::new("bloomfilter")? + .params(json!({"number_of_items": 4096}))?; +tbl.create_index(&["id"], Index::Plugin(bloom_filter)) + .execute() + .await?; +``` + + +An unknown plugin name or invalid parameters cause index creation to fail. + ## Index UUID Columns LanceDB supports scalar indexes on UUID columns (stored as `FixedSizeBinary(16)`), enabling efficient lookups and filtering on UUID-based primary keys. diff --git a/docs/web/quickstart.mdx b/docs/web/quickstart.mdx index c01686c2c..22fd4bd9d 100644 --- a/docs/web/quickstart.mdx +++ b/docs/web/quickstart.mdx @@ -5,7 +5,7 @@ description: "Install LanceDB, create a table, and run your first vector search. icon: rocket --- import { PyConnect, TsConnect, RsConnect, PyConnectObjectStorage, TsConnectObjectStorage, RsConnectObjectStorage, PyConnectEnterprisePlaceholders, TsConnectEnterprisePlaceholders, RsConnectEnterprisePlaceholders } from '/snippets/connection.mdx'; -import { PyQuickstartData, PyQuickstartCreateTable, PyQuickstartAddData, PyQuickstartCurateSample, PyQuickstartCurateDedupeSetup, PyQuickstartCurateDedupe, PyQuickstartCurateDedupeQuery, PyQuickstartFlattenStats, PyQuickstartAddFeature, PyQuickstartAddFeatureEnterprise, PyQuickstartMultimodalBytes, PyQuickstartTraining, TsQuickstartData, TsQuickstartCreateTable, TsQuickstartAddData, TsQuickstartVectorSearch1, TsQuickstartMultimodalBytes, RsQuickstartDefineStruct, RsQuickstartData, RsQuickstartCreateTable, RsQuickstartAddData, RsQuickstartVectorSearch1, RsQuickstartMultimodalBytes } from '/snippets/quickstart.mdx'; +import { PyQuickstartData, PyQuickstartCreateTable, PyQuickstartAddData, PyQuickstartCurateSample, PyQuickstartCurateDedupeSetup, PyQuickstartCurateDedupe, PyQuickstartCurateDedupeQuery, PyQuickstartFlattenStats, PyQuickstartAddFeature, PyQuickstartMultimodalBytes, PyQuickstartTraining, TsQuickstartData, TsQuickstartCreateTable, TsQuickstartAddData, TsQuickstartVectorSearch1, TsQuickstartMultimodalBytes, RsQuickstartDefineStruct, RsQuickstartData, RsQuickstartCreateTable, RsQuickstartAddData, RsQuickstartVectorSearch1, RsQuickstartMultimodalBytes } from '/snippets/quickstart.mdx'; This quickstart walks you through creating a table, searching your data, and preparing it for training. By default, it uses LanceDB Embedded with a local database, so no account or API key is required. @@ -324,7 +324,9 @@ Enterprise feature. If you're using LanceDB Embedded, skip ahead to Register a UDF as a Function, then call it to fill a column computed from -those flattened fields. This fills every existing row once, immediately: +those flattened fields. On LanceDB Enterprise a refresh runs as a server job: +`refresh_column_async` starts it and returns a job handle, and `wait()` blocks +until every existing row is filled: @@ -340,13 +342,7 @@ Read it back like any other column: -`refresh_column` fills only rows added since the last refresh and recomputes rows whose inputs changed, leaving unchanged rows alone. Run the same refresh as a background job instead, so it doesn't block: - - - - {PyQuickstartAddFeatureEnterprise} - - +Run the same refresh again after adding rows. It fills only rows added since the last refresh and recomputes rows whose inputs changed, leaving unchanged rows alone. To keep working while it runs, call `wait()` later, when you need the column filled. See [Create a Function](/curation/create-function) for UDFs that call external models or services, and [Computed columns](/feature-engineering/add-computed-column) diff --git a/docs/web/search/vector-search.mdx b/docs/web/search/vector-search.mdx index 2c37fef43..bdad76889 100644 --- a/docs/web/search/vector-search.mdx +++ b/docs/web/search/vector-search.mdx @@ -126,7 +126,8 @@ For indexed search, supported distance metrics vary by index type: ### Configure Distance Metric Without a vector index, searches use `l2` by default. You can specify `cosine` or -`dot` instead (`hamming` is supported for `IVF_FLAT` indexes only). +`dot` instead. For binary vectors, specify `hamming` even without an index. If +you build an index for Hamming search, use `IVF_FLAT`. When a vector index exists, the search metric must match the metric used to build the index. If you explicitly request a different metric, LanceDB cannot use that diff --git a/docs/web/snippets/quickstart.mdx b/docs/web/snippets/quickstart.mdx index a8b638085..15e999dbd 100644 --- a/docs/web/snippets/quickstart.mdx +++ b/docs/web/snippets/quickstart.mdx @@ -2,9 +2,7 @@ export const PyQuickstartAddData = "table.add(\n [\n {\n \"frame_id\": \"4\",\n \"video_id\": \"clip-2\",\n \"caption\": \"a gripper lowering a cup onto the table\",\n \"stats\": {\"motion\": 5, \"sharpness\": 4, \"exposure\": 4, \"framing\": 2},\n \"embedding\": [0.3, 0.9, 0.6, 0.8],\n }\n ]\n)\n"; -export const PyQuickstartAddFeature = "from lancedb import col, function\n\n@function\ndef quality_score(\n motion: float, sharpness: float, exposure: float, framing: float\n) -> float:\n return (motion + sharpness + exposure + framing) / 4.0\n\nversion = db.create_function_async(quality_score).wait()\ntable.add_columns(\n {\n \"quality_score\": version(\n motion=col(\"motion\"),\n sharpness=col(\"sharpness\"),\n exposure=col(\"exposure\"),\n framing=col(\"framing\"),\n )\n }\n)\ntable.refresh_column(\"quality_score\")\n"; - -export const PyQuickstartAddFeatureEnterprise = "job = table.refresh_column_async(\"quality_score\")\njob.wait()\n"; +export const PyQuickstartAddFeature = "from lancedb import col, function\n\n@function\ndef quality_score(\n motion: float, sharpness: float, exposure: float, framing: float\n) -> float:\n return (motion + sharpness + exposure + framing) / 4.0\n\nversion = db.create_function_async(quality_score).wait()\ntable.add_columns(\n {\n \"quality_score\": version(\n motion=col(\"motion\"),\n sharpness=col(\"sharpness\"),\n exposure=col(\"exposure\"),\n framing=col(\"framing\"),\n )\n }\n)\njob = table.refresh_column_async(\"quality_score\")\njob.wait()\n"; export const PyQuickstartCreateTable = "table = db.create_table(\"frames\", data=data, mode=\"overwrite\")\n"; diff --git a/docs/web/tools/cli.mdx b/docs/web/tools/cli.mdx index 92730a9f0..23000d88c 100644 --- a/docs/web/tools/cli.mdx +++ b/docs/web/tools/cli.mdx @@ -18,8 +18,21 @@ statements supported by your deployment. ## Install -On Apple Silicon macOS or Linux (x86-64 or ARM64), run the hosted installer. -It downloads the latest stable CLI for your platform, verifies the archive's +On Apple Silicon macOS or Linux (x86-64 or ARM64), install the CLI with +Homebrew or the hosted shell installer. + +### Homebrew + +```sh +brew install lancedb/tap/lancedb +lancedb --version +``` + +To upgrade an existing Homebrew installation, run `brew upgrade lancedb/tap/lancedb`. + +### Shell installer + +The installer downloads the latest stable CLI for your platform, verifies the archive's SHA-256 checksum, and installs the executable in `$HOME/.local/bin`. ```sh diff --git a/docs/web/training/permutation.mdx b/docs/web/training/permutation.mdx index 1f2f31596..6f38d226c 100644 --- a/docs/web/training/permutation.mdx +++ b/docs/web/training/permutation.mdx @@ -165,6 +165,49 @@ dataloader = torch.utils.data.DataLoader(permutation, collate_fn=lambda x: x) ``` +## Transforming rows with map {#transforming-rows-with-map} + +To change rows in Python as they are read, call `map()` with a function that takes a row as a dict and returns a dict. +Calls can be chained, and the functions run in order. Pass `batched=True` to receive the whole batch as a dict of +column lists instead; the function must then return one value per input row for every column. + + +```python Python icon="python" +import lancedb +import pyarrow as pa +from lancedb.permutation import Permutation + +db = lancedb.connect("memory://") +reviews = db.create_table( + "reviews", + pa.table({"text": ["Great", "Awful", "Fine"], "stars": [5, 1, 3]}), +) + + +def lowercase(row): + return {"text": row["text"].lower(), "stars": row["stars"]} + + +def add_label(batch): + return {**batch, "label": [int(stars >= 3) for stars in batch["stars"]]} + + +permutation = Permutation.identity(reviews).map(lowercase).map(add_label, batched=True) + +print(permutation.take_offsets([0, 1])) +# [{'text': 'great', 'stars': 5, 'label': 1}, {'text': 'awful', 'stars': 1, 'label': 0}] +``` + + +The dict a function returns replaces the row. A column the function does not return is dropped, so return every +column you want to keep. A mapped `Permutation` always produces a list of dicts, like the default format, whether or +not `batched` is set, so PyTorch's default collate function can batch it. `select_columns()` and `schema` still +describe the columns read from the table, which are the input of the first function. + +`map()` cannot be combined with `with_format()` or `with_transform()`. Calling one after the other, in either order, +raises a `ValueError`. To build tensors from mapped rows, convert them in the DataLoader's `collate_fn`. When +`num_workers > 0`, pass picklable top-level functions to `map()`, not lambdas. + ## Selecting columns {#selecting-columns} By default, the `Table` class will return all columns in the table when used as input to PyTorch. If you only need diff --git a/java/lancedb-core/pom.xml b/java/lancedb-core/pom.xml index 46ffa789d..4f548299f 100644 --- a/java/lancedb-core/pom.xml +++ b/java/lancedb-core/pom.xml @@ -37,12 +37,12 @@ arrow-memory-netty - + org.apache.httpcomponents.client5 httpclient5 - 5.2.1 + 5.6.5 diff --git a/java/pom.xml b/java/pom.xml index 860d64fd0..64505b7bd 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -28,7 +28,7 @@ UTF-8 15.0.0 - 15.0.0-beta.32 + 15.0.0-beta.34 2.18.12 false 2.30.0 diff --git a/nodejs/__test__/remote.test.ts b/nodejs/__test__/remote.test.ts index 9dca563e3..35e1d608c 100644 --- a/nodejs/__test__/remote.test.ts +++ b/nodejs/__test__/remote.test.ts @@ -1595,6 +1595,91 @@ describe("remote connection", () => { ]); }); + it("uses an explicit type and nested params for remote scalar plugin indexes", async () => { + const createIndexBodies: Record[] = []; + + await withMockDatabase( + (req, res) => { + const path = req.url ?? ""; + if (path.endsWith("/describe/")) { + res.writeHead(200, { "Content-Type": "application/json" }).end( + JSON.stringify({ + name: "t", + version: 1, + schema: { + fields: [ + { name: "id", type: { type: "int32" }, nullable: false }, + ], + }, + }), + ); + return; + } + + if (path.endsWith("/create_index/")) { + let raw = ""; + req.on("data", (chunk) => { + raw += chunk; + }); + req.on("end", () => { + createIndexBodies.push(JSON.parse(raw)); + res.writeHead(200).end(); + }); + return; + } + + res.writeHead(404).end(); + }, + async (db) => { + const table = await db.openTable("t"); + await table.createIndex("id", { config: Index.plugin(" ZoneMap ") }); + await table.createIndex("id", { + config: Index.plugin("bloomfilter", { + // biome-ignore lint/style/useNamingConvention: plugin param name + number_of_items: 4096, + column: "not_id", + }), + name: "id_bloom", + }); + await table.createIndex("id", { + config: Index.plugin("bloomfilter", '{"probability": 0.01}'), + }); + await table.createIndex("id", { config: Index.plugin("zonemap", {}) }); + }, + ); + + expect(createIndexBodies).toEqual([ + // biome-ignore lint/style/useNamingConvention: wire format + { column: "id", index_type: "PLUGIN", plugin_type: "ZONEMAP" }, + { + column: "id", + // biome-ignore lint/style/useNamingConvention: wire format + index_type: "PLUGIN", + // biome-ignore lint/style/useNamingConvention: wire format + plugin_type: "BLOOMFILTER", + name: "id_bloom", + // biome-ignore lint/style/useNamingConvention: plugin param name + params: { number_of_items: 4096, column: "not_id" }, + }, + { + column: "id", + // biome-ignore lint/style/useNamingConvention: wire format + index_type: "PLUGIN", + // biome-ignore lint/style/useNamingConvention: wire format + plugin_type: "BLOOMFILTER", + params: { probability: 0.01 }, + }, + { + column: "id", + // biome-ignore lint/style/useNamingConvention: wire format + index_type: "PLUGIN", + // biome-ignore lint/style/useNamingConvention: wire format + plugin_type: "ZONEMAP", + params: {}, + }, + ]); + }); + it("diffs and cherry-picks remote branches", async () => { const sampleDiff = { fromBranch: "exp", diff --git a/nodejs/__test__/table.test.ts b/nodejs/__test__/table.test.ts index 1f3cff276..afd0e1741 100644 --- a/nodejs/__test__/table.test.ts +++ b/nodejs/__test__/table.test.ts @@ -1933,6 +1933,74 @@ describe("When creating an index", () => { }); }); + test.each([ + ["ZoneMap", undefined, "ZoneMap"], + ["BTREE", undefined, "BTree"], + [ + "bloomfilter", + // biome-ignore lint/style/useNamingConvention: plugin param name + { number_of_items: 64, probability: 0.01 }, + "BloomFilter", + ], + ["bloomfilter", '{"number_of_items": 64}', "BloomFilter"], + ])( + "create a scalar plugin index by name (%s, %p)", + async (indexType, params, expectedType) => { + await tbl.createIndex("id", { + config: Index.plugin(indexType, params), + name: "id_plugin", + }); + + const indices = await tbl.listIndices(); + expect(indices).toHaveLength(1); + expect(indices[0].name).toBe("id_plugin"); + expect(indices[0].indexType).toBe(expectedType); + expect(indices[0].columns).toEqual(["id"]); + + const query = tbl.query().where("id = 42"); + expect(await query.explainPlan()).toContain("ScalarIndexQuery"); + expect(await query.toArray()).toHaveLength(1); + }, + ); + + test("lists a scalar plugin without a LanceDB type by its own name", async () => { + const db = await connect(tmpDir.name); + const textTbl = await db.createTable("minhash", [ + { text: "alpha beta" }, + { text: "beta gamma" }, + ]); + await textTbl.createIndex("text", { config: Index.plugin("minhashlsh") }); + + const indices = await textTbl.listIndices(); + expect(indices).toHaveLength(1); + expect(indices[0].indexType).toBe("MinHashLsh"); + }); + + test("rejects invalid scalar plugin configs", async () => { + expect(() => Index.plugin("")).toThrow("must not be empty"); + expect(() => Index.plugin(" ")).toThrow("must not be empty"); + expect(() => Index.plugin("zonemap", "[1]")).toThrow( + "must be a JSON object, got an array", + ); + expect(() => Index.plugin("zonemap", "null")).toThrow( + "must be a JSON object, got null", + ); + expect(() => Index.plugin("zonemap", "{not json")).toThrow( + "not valid JSON", + ); + expect(() => + Index.plugin("zonemap", [1] as unknown as Record), + ).toThrow("must be a JSON object, got an array"); + + await expect( + tbl.createIndex("id", { config: Index.plugin("NoSuchPlugin") }), + ).rejects.toThrow("No scalar index plugin found for name 'nosuchplugin'"); + await expect( + tbl.createIndex("id", { config: Index.plugin("ngram") }), + ).rejects.toThrow(/ngram/i); + expect(await tbl.listIndices()).toHaveLength(0); + }); + test("should be able to get index stats", async () => { await tbl.createIndex("id"); diff --git a/nodejs/lancedb/indices.ts b/nodejs/lancedb/indices.ts index d743827da..23536bb07 100644 --- a/nodejs/lancedb/indices.ts +++ b/nodejs/lancedb/indices.ts @@ -893,6 +893,37 @@ export class Index { return new Index(LanceDbIndex.rtree(pageSize)); } + /** + * Create a scalar index of a type recognized by a registered database plugin. + * + * Use this for index types without a dedicated factory on `Index`. + * Prefer a dedicated factory when one is available. + * + * An unknown plugin name or invalid parameters cause `createIndex` to fail. + * + * @param indexType - The index type, case-insensitive. + * Surrounding whitespace is ignored. Must not be empty. + * @param params - The index parameters, as an object or as a string + * holding a JSON object. They are passed as given. Each plugin defines + * its parameters and defaults; refer to the plugin's documentation + * for guidance. + * @throws If `indexType` is empty, or `params` is not a JSON object. + * + * @example + * ```ts + * await table.createIndex("id", { + * config: Index.plugin("bloomfilter", { number_of_items: 4096 }), + * }); + * ``` + */ + static plugin(indexType: string, params?: Record | string) { + const paramsJson = + params === undefined || typeof params === "string" + ? params + : JSON.stringify(params); + return new Index(LanceDbIndex.plugin(indexType, paramsJson)); + } + /** * Create a full text search index * diff --git a/nodejs/src/index.rs b/nodejs/src/index.rs index 80107b0b4..638d4856f 100644 --- a/nodejs/src/index.rs +++ b/nodejs/src/index.rs @@ -5,7 +5,7 @@ use std::sync::Mutex; use lancedb::index::Index as LanceDbIndex; use lancedb::index::scalar::{ - BTreeIndexBuilder, FmIndexBuilder, FtsIndexBuilder, RTreeIndexBuilder, + BTreeIndexBuilder, FmIndexBuilder, FtsIndexBuilder, PluginIndexBuilder, RTreeIndexBuilder, }; use lancedb::index::vector::{ IvfFlatIndexBuilder, IvfHnswPqIndexBuilder, IvfHnswSqIndexBuilder, IvfPqIndexBuilder, @@ -228,6 +228,18 @@ impl Index { } } + /// `params_json`, if set, must be a string holding a JSON object. + #[napi(factory)] + pub fn plugin(index_type: String, params_json: Option) -> napi::Result { + let mut builder = PluginIndexBuilder::new(index_type).default_error()?; + if let Some(params_json) = params_json { + builder = builder.params_json(params_json).default_error()?; + } + Ok(Self { + inner: Mutex::new(Some(LanceDbIndex::Plugin(builder))), + }) + } + #[napi(factory)] pub fn rtree(page_size: Option) -> napi::Result { let mut builder = RTreeIndexBuilder::default(); diff --git a/nodejs/src/table.rs b/nodejs/src/table.rs index 5b1153909..1370278b0 100644 --- a/nodejs/src/table.rs +++ b/nodejs/src/table.rs @@ -1314,7 +1314,12 @@ pub struct IndexConfig { impl From for IndexConfig { fn from(value: lancedb::index::IndexConfig) -> Self { - let index_type = format!("{:?}", value.index_type); + // A registered plugin's type is its display name, such as "MinHashLsh", + // which `Debug` would render as `Custom("MinHashLsh")`. + let index_type = match value.index_type { + lancedb::index::IndexType::Custom(name) => name, + index_type => format!("{index_type:?}"), + }; Self { index_type, columns: value.columns, diff --git a/python/pyproject.toml b/python/pyproject.toml index 14240d087..ab35e66df 100644 --- a/python/pyproject.toml +++ b/python/pyproject.toml @@ -64,7 +64,7 @@ tests = [ "polars>=0.19, <=1.32.3", "pyarrow>=16", "pyarrow-stubs>=16.0", - "pylance==15.0.0b32", + "pylance==15.0.0b34", "requests>=2.31.0", "datafusion>=54,<55", "opentelemetry-sdk>=1.30.0", @@ -75,7 +75,7 @@ dev = [ "pyright>=1.1.350", "maturin>=1.10", ] -docs = ["mkdocs", "mkdocs-jupyter", "mkdocs-material", "mkdocstrings-python"] +docs = ["mkdocs", "mkdocs-jupyter", "mkdocs-material>=9.8.2", "mkdocstrings[python]>=1.0.7,<2"] clip = ["torch", "pillow>=13.0.0", "open-clip-torch"] siglip = ["torch", "pillow>=13.0.0", "transformers>=4.41.0","sentencepiece"] embeddings = [ diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index 12bd81fdd..638b0bede 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -27,6 +27,7 @@ from .index import ( NGram, ZoneMap, RTree, + ScalarPlugin, HnswPq, HnswSq, HnswFlat, @@ -682,6 +683,7 @@ class Table: NGram, ZoneMap, RTree, + ScalarPlugin, FTS, ], replace: Optional[bool], @@ -708,6 +710,7 @@ class Table: NGram, ZoneMap, RTree, + ScalarPlugin, FTS, ], replace: Optional[bool], diff --git a/python/python/lancedb/embeddings/openai.py b/python/python/lancedb/embeddings/openai.py index 8592598cc..a8e652789 100644 --- a/python/python/lancedb/embeddings/openai.py +++ b/python/python/lancedb/embeddings/openai.py @@ -99,8 +99,6 @@ class OpenAIEmbeddings(TextEmbeddingFunction): texts: list[str] or np.ndarray (of str) The texts to embed """ - openai = attempt_import_or_raise("openai") - valid_texts = [] valid_indices = [] for idx, text in enumerate(texts): @@ -108,6 +106,11 @@ class OpenAIEmbeddings(TextEmbeddingFunction): valid_texts.append(text) valid_indices.append(idx) + if not valid_texts: + return [None] * len(texts) + + openai = attempt_import_or_raise("openai") + # TODO retry, rate limit, token limit def embed_batch(texts_batch, indices_batch): kwargs = { diff --git a/python/python/lancedb/index.py b/python/python/lancedb/index.py index 321a1b151..2b5dd8ff2 100644 --- a/python/python/lancedb/index.py +++ b/python/python/lancedb/index.py @@ -2,7 +2,8 @@ # SPDX-FileCopyrightText: Copyright The LanceDB Authors from dataclasses import dataclass -from typing import List, Literal, Optional +import json +from typing import Any, Dict, List, Literal, Optional, Union from ._lancedb import ( IndexConfig, @@ -186,6 +187,84 @@ class RTree: page_size: Optional[int] = None +@dataclass +class ScalarPlugin: + """Configure a scalar index of a type recognized by a registered database plugin. + + Use this for index types without a dedicated configuration class. + Prefer a dedicated class, such as [BTree][lancedb.index.BTree], when one + is available. + + An unknown plugin name or invalid parameters cause index creation to fail. + + Examples + -------- + >>> from lancedb.index import ScalarPlugin + >>> ScalarPlugin("bloomfilter", params={"number_of_items": 4096}) + ScalarPlugin(index_type='bloomfilter', params={'number_of_items': 4096}) + + Pass it as ``config`` to ``create_index``: + + >>> table.create_index( # doctest: +SKIP + ... "id", + ... config=ScalarPlugin("bloomfilter", '{"probability": 0.01}'), + ... ) + + Attributes + ---------- + index_type: str + The index type, case-insensitive. Surrounding whitespace is ignored. + Must not be empty. + params: dict or str, optional + The index parameters, as a dict or as a string holding a JSON object. + They are passed as given. Each plugin defines its parameters and + defaults; refer to the plugin's documentation for guidance. + + Raises + ------ + ValueError + If ``index_type`` is empty, or ``params`` is a string that is not a + JSON object. + TypeError + If ``index_type`` is not a string, or ``params`` is not a dict, a + string or None. + """ + + index_type: str + params: Optional[Union[Dict[str, Any], str]] = None + + def __post_init__(self): + if not isinstance(self.index_type, str): + raise TypeError( + "ScalarPlugin index_type must be a str, got " + + type(self.index_type).__name__ + ) + if not self.index_type.strip(): + raise ValueError("ScalarPlugin index_type must not be empty") + if isinstance(self.params, str): + try: + parsed = json.loads(self.params) + except json.JSONDecodeError as e: + raise ValueError(f"ScalarPlugin params are not valid JSON: {e}") from e + if not isinstance(parsed, dict): + raise ValueError( + "ScalarPlugin params must be a JSON object, got " + + type(parsed).__name__ + ) + elif self.params is not None and not isinstance(self.params, dict): + raise TypeError( + "ScalarPlugin params must be a dict, a JSON string or None, got " + + type(self.params).__name__ + ) + + @property + def _params_json(self) -> Optional[str]: + # Read by the native layer, which checks again that this is an object. + if self.params is None or isinstance(self.params, str): + return self.params + return json.dumps(self.params) + + @dataclass class FTS: """Describe a FTS index configuration. @@ -1041,4 +1120,5 @@ __all__ = [ "Fm", "NGram", "RTree", + "ScalarPlugin", ] diff --git a/python/python/lancedb/permutation.py b/python/python/lancedb/permutation.py index ff1cf7b59..1656548ec 100644 --- a/python/python/lancedb/permutation.py +++ b/python/python/lancedb/permutation.py @@ -512,6 +512,88 @@ class Transforms: # HuggingFace uses 10 which is pretty small DEFAULT_BATCH_SIZE = 100 +_MAP_FORMAT_ERROR = ( + "map cannot be combined with with_format or with_transform; convert the " + "output inside the map callback or in the DataLoader collate_fn instead" +) + + +def _map_rows(data: Any, num_rows: int) -> list[dict[str, Any]]: + """Return the data flowing through a map chain as a list of row dicts.""" + if isinstance(data, pa.RecordBatch): + return data.to_pylist() + if isinstance(data, dict): + return [ + {name: values[i] for name, values in data.items()} for i in range(num_rows) + ] + return data + + +def _map_columns(data: Any) -> dict[str, Any]: + """Return the data flowing through a map chain as a dict of columns.""" + if isinstance(data, pa.RecordBatch): + return data.to_pydict() + if isinstance(data, list): + names = data[0].keys() + if any(row.keys() != names for row in data): + raise ValueError( + "Cannot pass rows to a batched map callback because the previous " + "callback did not return the same keys for every row" + ) + return {name: [row[name] for row in data] for name in names} + return data + + +class _MapTransform: + """ + The transform installed by [map][lancedb.permutation.Permutation.map] + + Each step is a ``(fn, batched)`` pair. This is a module-level class, and not a + closure, so that a mapped permutation pickles whenever its callbacks do. + """ + + def __init__(self, steps: tuple[tuple[Callable, bool], ...]): + self.steps = steps + + def __call__(self, batch: pa.RecordBatch) -> list[dict[str, Any]]: + num_rows = batch.num_rows + if num_rows == 0: + return [] + + # The layout is only converted when a callback needs the other one + data = batch + for fn, batched in self.steps: + if batched: + data = fn(_map_columns(data)) + if not isinstance(data, dict): + raise TypeError( + "A batched map callback must return a dict of columns, " + f"got {type(data).__name__}" + ) + for name, values in data.items(): + # A str or dict can be indexed but is not a column of values + if isinstance(values, (str, bytes, dict)) or not hasattr( + values, "__getitem__" + ): + raise TypeError( + "A batched map callback must return a list of values " + f"for column `{name}`, got {type(values).__name__}" + ) + if len(values) != num_rows: + raise ValueError( + f"A batched map callback returned {len(values)} values " + f"for column `{name}` but the batch has {num_rows} rows" + ) + else: + data = [fn(row) for row in _map_rows(data, num_rows)] + for row in data: + if not isinstance(row, dict): + raise TypeError( + "A map callback must return a dict for each row, " + f"got {type(row).__name__}" + ) + return _map_rows(data, num_rows) + def _is_persisted_plan(table: Table) -> bool: """Whether a permutation table lives in reopenable storage rather than memory.""" @@ -619,6 +701,9 @@ class Permutation: self.split = split self.selection = selection self.transform_fn = transform_fn + # Whether the default transform was replaced, by with_format, by + # with_transform, or by a caller passing its own transform here + self._explicit_transform = transform_fn is not Transforms.arrow2python self.batch_size = batch_size self.offset = offset self.limit = limit @@ -881,6 +966,7 @@ class Permutation: "selection": self.selection, "batch_size": self.batch_size, "transform_fn": self.transform_fn, + "explicit_transform": self._explicit_transform, "offset": self.offset, "limit": self.limit, "connection_factory": self.connection_factory, @@ -953,6 +1039,11 @@ class Permutation: self.selection = state["selection"] self.batch_size = state["batch_size"] self.transform_fn = state["transform_fn"] + # Pickles written before this flag existed still carry their transform. + # Anything but the default must have been set explicitly. + self._explicit_transform = state.get( + "explicit_transform", self.transform_fn is not Transforms.arrow2python + ) self.offset = state["offset"] self.limit = state["limit"] self.connection_factory = connection_factory @@ -1304,8 +1395,16 @@ class Permutation: For custom formatting, use [with_transform][lancedb.permutation.Permutation.with_transform] which overrides this method. + + A format cannot be combined with + [map][lancedb.permutation.Permutation.map], which always yields a list + of dicts. Doing so raises a ValueError. """ assert format is not None, "format is required" + # Checked before with_transform does, so that a format with an optional + # dependency cannot fail on its import first + if isinstance(self.transform_fn, _MapTransform): + raise ValueError(_MAP_FORMAT_ERROR) if format == "python": return self.with_transform(Transforms.arrow2python) if format == "python_col": @@ -1338,10 +1437,109 @@ class Permutation: Note: transforms are not invoked in parallel. This method is not a good place for expensive operations such as image decoding. + + For a higher-level API that works with Python dicts, see + [map][lancedb.permutation.Permutation.map]. A transform cannot be combined + with ``map``. Doing so raises a ValueError. """ assert transform is not None, "transform is required" + if isinstance(self.transform_fn, _MapTransform): + raise ValueError(_MAP_FORMAT_ERROR) new = copy.copy(self) new.transform_fn = transform + new._explicit_transform = True + return new + + def map( + self, + fn: Callable[[dict[str, Any]], dict[str, Any]], + *, + batched: bool = False, + ) -> "Permutation": + """ + Apply a function to the rows of the permutation + + This is a dict-based alternative to + [with_transform][lancedb.permutation.Permutation.with_transform], loosely + modeled after the huggingface ``Dataset.map``. It is lazy: ``fn`` is not + called until data is read. + + Calls to ``map`` can be chained. The callbacks run in order and the dict + returned by a callback replaces the row entirely, so the next callback only + sees what the previous one returned. Unlike the huggingface method, the + returned dict is not merged into the row: return every column to keep. + + A mapped permutation always yields a list of dicts (one per row) for each + batch, which is the same shape as the default "python" format. ``batched`` + only controls what ``fn`` receives. Rows keep their position, so a callback + cannot add, drop, or reorder rows. + + Since ``map`` decides the output format it cannot be combined with + [with_format][lancedb.permutation.Permutation.with_format] or + [with_transform][lancedb.permutation.Permutation.with_transform]. Calling + one after the other, in either order, raises a ValueError. Convert the + mapped rows to tensors in the DataLoader ``collate_fn`` instead. + + [select_columns][lancedb.permutation.Permutation.select_columns], + [remove_columns][lancedb.permutation.Permutation.remove_columns], + [rename_column][lancedb.permutation.Permutation.rename_column] and + [schema][lancedb.permutation.Permutation.schema] describe the columns read + from the base table, which are the input of the first callback. They do + not describe the output of ``map``, whether they are used before or after it. + + Parameters + ---------- + fn: Callable + The function to apply. It receives and returns a single row as a dict + mapping column names to values. If ``batched`` is True it instead + receives and returns a whole batch as a dict mapping column names to + lists of values, and every returned column must have one value per + input row. + + DataLoader workers started with ``spawn`` or ``forkserver`` receive a + pickled copy of the permutation, so ``fn`` must then be picklable. + Use a top-level function; lambdas and local functions do not pickle. + batched: bool, default False + Whether ``fn`` is called once per batch instead of once per row. + + Examples + -------- + >>> import lancedb + >>> db = lancedb.connect("memory:///") + >>> tbl = db.create_table("tbl", data=[{"x": x} for x in range(3)]) + >>> def add_y(row): + ... return {**row, "y": row["x"] * 2} + >>> def add_z(batch): + ... return {**batch, "z": [x + y for x, y in zip(batch["x"], batch["y"])]} + >>> permutation = Permutation.identity(tbl).map(add_y).map(add_z, batched=True) + >>> permutation.take_offsets([0, 1]) + [{'x': 0, 'y': 0, 'z': 0}, {'x': 1, 'y': 2, 'z': 3}] + + With a PyTorch DataLoader, a ``collate_fn`` turns the mapped rows of each + batch into tensors:: + + import torch + + def collate(rows): + return { + "x": torch.tensor([row["x"] for row in rows]), + "z": torch.tensor([row["z"] for row in rows]), + } + + dataloader = torch.utils.data.DataLoader( + permutation, batch_size=32, shuffle=True, collate_fn=collate + ) + """ + if not callable(fn): + raise TypeError("fn must be callable") + if self._explicit_transform: + raise ValueError(_MAP_FORMAT_ERROR) + + steps = ((fn, batched),) + if isinstance(self.transform_fn, _MapTransform): + steps = self.transform_fn.steps + steps + new = copy.copy(self) + new.transform_fn = _MapTransform(steps) return new def take_offsets(self, offsets: list[int]) -> Any: @@ -1349,8 +1547,8 @@ class Permutation: Take rows from the permutation by offset The returned value is passed through the permutation's current transform, - so `with_format` and `with_transform` affect this method in the same way - they affect iteration. + so `with_format`, `with_transform`, and `map` affect this method in the + same way they affect iteration. """ self._ensure_open() diff --git a/python/python/lancedb/remote/table.py b/python/python/lancedb/remote/table.py index 715804e4b..04e0190a3 100644 --- a/python/python/lancedb/remote/table.py +++ b/python/python/lancedb/remote/table.py @@ -619,7 +619,7 @@ class RemoteTable(Table): config : IndexConfigType, optional The index configuration object. If provided, uses the new unified API. Can be one of: IvfFlat, IvfPq, IvfSq, IvfRq, HnswPq, HnswSq, - BTree, Bitmap, LabelList, Fm, NGram, ZoneMap, RTree, FTS. + BTree, Bitmap, LabelList, Fm, NGram, ZoneMap, RTree, ScalarPlugin, FTS. replace : bool, default True Whether to replace an existing index on this column. wait_timeout : timedelta, optional diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index fad89db49..ff8820633 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -82,6 +82,7 @@ from .index import ( NGram, ZoneMap, RTree, + ScalarPlugin, HnswPq, HnswSq, HnswFlat, @@ -354,6 +355,7 @@ IndexConfigType = Union[ NGram, ZoneMap, RTree, + ScalarPlugin, FTS, ] @@ -2028,7 +2030,7 @@ class Table(ABC): config : IndexConfigType, optional The index configuration object. If provided, uses the new unified API. Can be one of: IvfFlat, IvfPq, IvfSq, IvfRq, HnswPq, HnswSq, - BTree, Bitmap, LabelList, Fm, NGram, ZoneMap, RTree, FTS. + BTree, Bitmap, LabelList, Fm, NGram, ZoneMap, RTree, ScalarPlugin, FTS. replace : bool, default True Whether to replace an existing index on this column. exist_ok : bool, default False @@ -5162,7 +5164,7 @@ class LanceTable(Table): config : IndexConfigType, optional The index configuration object. If provided, uses the new unified API. Can be one of: IvfFlat, IvfPq, IvfSq, IvfRq, HnswPq, HnswSq, - BTree, Bitmap, LabelList, Fm, NGram, ZoneMap, RTree, FTS. + BTree, Bitmap, LabelList, Fm, NGram, ZoneMap, RTree, ScalarPlugin, FTS. replace : bool, default True Whether to replace an existing index on this column. exist_ok : bool, default False @@ -7873,6 +7875,7 @@ class AsyncTable: NGram, ZoneMap, RTree, + ScalarPlugin, FTS, ] ] = None, @@ -7955,13 +7958,14 @@ class AsyncTable: NGram, ZoneMap, RTree, + ScalarPlugin, FTS, ), ): raise TypeError( "config must be an instance of IvfSq, IvfPq, IvfRq, HnswPq, HnswSq," - " BTree, Bitmap, LabelList, Fm, NGram, ZoneMap, RTree, or FTS," - " but got " + str(type(config)) + " BTree, Bitmap, LabelList, Fm, NGram, ZoneMap, RTree," + " ScalarPlugin, or FTS, but got " + str(type(config)) ) try: await self._inner.create_index( @@ -8002,6 +8006,7 @@ class AsyncTable: NGram, ZoneMap, RTree, + ScalarPlugin, FTS, ] ] = None, diff --git a/python/python/tests/test_embeddings.py b/python/python/tests/test_embeddings.py index 78cd76ad2..488fd3cd9 100644 --- a/python/python/tests/test_embeddings.py +++ b/python/python/tests/test_embeddings.py @@ -1107,6 +1107,47 @@ def test_openai_bad_request_partial_batch_recovery(): assert embeddings[1] is None +@pytest.fixture +def mock_openai_client(monkeypatch): + client = MagicMock() + client.embeddings.create.return_value.data = [] + monkeypatch.setattr( + "lancedb.embeddings.openai.attempt_import_or_raise", MagicMock() + ) + monkeypatch.setattr(get_registry().get("openai"), "_openai_client", client) + return client + + +@pytest.mark.parametrize( + ("texts", "expected"), + [([], []), ([None, ""], [None, None])], + ids=["empty-batch", "all-inputs-filtered"], +) +def test_openai_skips_batches_without_valid_text(mock_openai_client, texts, expected): + model = get_registry().get("openai").create() + + assert model.compute_source_embeddings(texts) == expected + mock_openai_client.embeddings.create.assert_not_called() + + +def test_openai_add_all_invalid_texts_as_null_vectors(mock_openai_client, tmp_path): + model = get_registry().get("openai").create(name="text-embedding-3-small", dim=2) + + class TextModel(LanceModel): + text: Optional[str] = model.SourceField() + vector: Optional[Vector(model.ndims())] = model.VectorField() + + db = lancedb.connect(tmp_path) + table = db.create_table("words", schema=TextModel) + table.add([{"text": None}, {"text": ""}], on_bad_vectors="null") + + assert table.to_arrow().to_pylist() == [ + {"text": None, "vector": None}, + {"text": "", "vector": None}, + ] + mock_openai_client.embeddings.create.assert_not_called() + + def test_ollama_embeddings_pickle(): """OllamaEmbeddings must pickle even after the cached client is created.""" registry = get_registry() diff --git a/python/python/tests/test_index.py b/python/python/tests/test_index.py index fe90732be..c38948eb2 100644 --- a/python/python/tests/test_index.py +++ b/python/python/tests/test_index.py @@ -26,6 +26,7 @@ from lancedb.index import ( NGram, ZoneMap, RTree, + ScalarPlugin, HnswPq, HnswSq, HnswFlat, @@ -687,6 +688,132 @@ async def test_create_zonemap_index(db_async): assert sorted(result["id"].to_pylist()) == list(range(90, 100)) +def plugin_table_data(): + return pa.table( + {"id": [1, 2, 3, 4], "text": ["abc", "xyz", None, ""]}, + schema=pa.schema([("id", pa.int32()), ("text", pa.string())]), + ) + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "index_type, params, column, expected_type, predicate, expected_ids", + [ + ("ZoneMap", None, "id", "ZoneMap", "id >= 2 AND id < 4", [2, 3]), + (" BTREE ", None, "id", "BTree", "id = 3", [3]), + ( + "bloomfilter", + {"number_of_items": 2, "probability": 0.01}, + "text", + "BloomFilter", + "text = 'abc'", + [1], + ), + ( + "BloomFilter", + '{"number_of_items": 2}', + "text", + "BloomFilter", + "text = 'abc'", + [1], + ), + ], +) +async def test_create_scalar_plugin_index( + db_async, index_type, params, column, expected_type, predicate, expected_ids +): + # Lance's built-in plugins, created by name, are listed with the same type + # as their dedicated configs and serve the filters those configs serve. + table = await db_async.create_table("plugin_table", plugin_table_data()) + config = ScalarPlugin(index_type, params) + await table.create_index(column, config=config, name="plugin_idx") + + indices = await table.list_indices() + assert [(i.name, i.index_type, i.columns) for i in indices] == [ + ("plugin_idx", expected_type, [column]) + ] + stats = await table.index_stats("plugin_idx") + assert stats.num_indexed_rows == 4 + + query = table.query().where(predicate) + assert "ScalarIndexQuery" in await query.explain_plan() + result = await query.to_arrow() + assert sorted(result["id"].to_pylist()) == expected_ids + + +@pytest.mark.asyncio +async def test_scalar_plugin_without_lancedb_type_lists_plugin_name(db_async): + data = pa.table({"text": ["alpha beta", "beta gamma", "gamma delta"]}) + table = await db_async.create_table("minhash_table", data) + await table.create_index("text", config=ScalarPlugin("minhashlsh")) + + indices = await table.list_indices() + assert len(indices) == 1 + assert indices[0].index_type == "MinHashLsh" + assert 'index_type="MinHashLsh"' in repr(indices[0]) + stats = await table.index_stats(indices[0].name) + assert stats.index_type == "MinHashLsh" + + +def test_scalar_plugin_sync_table_and_job(tmp_path): + db = lancedb.connect(tmp_path) + table = db.create_table("plugin_table", plugin_table_data()) + + table.create_index("id", config=ScalarPlugin("zonemap")) + job = table.create_index_async( + "text", + config=ScalarPlugin("bloomfilter", {"probability": 0.01}), + name="text_bloom", + ) + job.wait() + + types = {index.name: index.index_type for index in table.list_indices()} + assert types == {"id_idx": "ZoneMap", "text_bloom": "BloomFilter"} + assert "ScalarIndexQuery" in table.search().where("text = 'abc'").explain_plan() + + +@pytest.mark.parametrize( + "kwargs, error, match", + [ + ({"index_type": ""}, ValueError, "must not be empty"), + ({"index_type": " "}, ValueError, "must not be empty"), + ({"index_type": None}, TypeError, "index_type must be a str"), + ({"index_type": "zonemap", "params": "[1]"}, ValueError, "got list"), + ({"index_type": "zonemap", "params": "null"}, ValueError, "got NoneType"), + ({"index_type": "zonemap", "params": "{x"}, ValueError, "not valid JSON"), + ({"index_type": "zonemap", "params": [1]}, TypeError, "got list"), + ({"index_type": "zonemap", "params": 1}, TypeError, "got int"), + ], +) +def test_scalar_plugin_rejects_invalid_config(kwargs, error, match): + with pytest.raises(error, match=match): + ScalarPlugin(**kwargs) + + +@pytest.mark.asyncio +async def test_scalar_plugin_errors_reach_the_caller(db_async): + table = await db_async.create_table("plugin_table", plugin_table_data()) + + # The native layer checks the params again, after the dataclass is mutated. + config = ScalarPlugin("zonemap") + config.params = "[1]" + with pytest.raises(ValueError, match="must be a JSON object, got an array"): + await table.create_index("id", config=config) + + with pytest.raises( + ValueError, match="No scalar index plugin found for name 'nosuchplugin'" + ): + await table.create_index("id", config=ScalarPlugin("NoSuchPlugin")) + with pytest.raises(ValueError, match="ngram index can only be created on a Utf8"): + await table.create_index("id", config=ScalarPlugin("ngram")) + with pytest.raises(RuntimeError, match='invalid type: string "many"'): + await table.create_index( + "text", + config=ScalarPlugin("bloomfilter", {"number_of_items": "many"}), + ) + assert await table.list_indices() == [] + + @pytest.mark.asyncio async def test_create_bitmap_index(some_table: AsyncTable): await some_table.create_index("id", config=Bitmap()) diff --git a/python/python/tests/test_permutation.py b/python/python/tests/test_permutation.py index 1e23d6d99..add877582 100644 --- a/python/python/tests/test_permutation.py +++ b/python/python/tests/test_permutation.py @@ -1856,3 +1856,244 @@ def test_from_tables_split_without_permutation_table(mem_db): with pytest.raises(ValueError, match="permutation on split `train` because no"): Permutation.from_tables(tbl, split="train") + + +def _double_value_row(row): + return {"id": row["id"], "value": row["value"] * 2} + + +def _double_value_batch(batch): + return {"id": batch["id"], "value": [value * 2 for value in batch["value"]]} + + +def test_map_row_by_row(some_permutation: Permutation): + """Test .map() applies fn to each row individually.""" + mapped = some_permutation.map(_double_value_row) + batches = list(mapped.iter(10, skip_last_batch=False)) + first_batch = batches[0] + assert len(first_batch) == 10 + assert isinstance(first_batch[0], dict) + for row in first_batch: + assert row["value"] == row["id"] * 2 + + +def test_map_batched(some_permutation: Permutation): + """Test batched only changes what fn receives, not what is yielded.""" + seen = [] + + def double_value(batch): + seen.append(batch) + return _double_value_batch(batch) + + mapped = some_permutation.map(double_value, batched=True) + first_batch = next(mapped.iter(10, skip_last_batch=False)) + assert isinstance(seen[0], dict) + assert len(seen[0]["id"]) == 10 + assert first_batch == next( + some_permutation.map(_double_value_row).iter(10, skip_last_batch=False) + ) + + +def test_map_chain(some_permutation: Permutation): + """Test chained maps run in order and each one replaces the whole row.""" + + def add_doubled(row): + return {**row, "doubled": row["value"] * 2} + + def to_total(batch): + return { + "total": [a + b for a, b in zip(batch["value"], batch["doubled"])], + } + + def add_label(row): + return {**row, "label": str(row["total"])} + + first = some_permutation.map(add_doubled) + mapped = first.map(to_total, batched=True).map(add_label) + expected = [ + {"total": row["value"] * 3, "label": str(row["value"] * 3)} + for row in some_permutation.take_offsets([0, 1, 2]) + ] + assert mapped.take_offsets([0, 1, 2]) == expected + assert next(mapped.iter(3, skip_last_batch=False)) == expected + # Extending a chain does not change the permutation it was derived from + assert set(first.take_offsets([0])[0]) == {"id", "value", "doubled"} + + +@pytest.mark.parametrize( + "explicit", + [ + lambda permutation: permutation.with_format("python"), + lambda permutation: permutation.with_format("arrow"), + lambda permutation: permutation.with_transform(Transforms.arrow2arrow), + ], +) +def test_map_rejects_format_and_transform(some_permutation: Permutation, explicit): + """Test .map() cannot be mixed with with_format or with_transform.""" + with pytest.raises(ValueError, match="map cannot be combined"): + explicit(some_permutation).map(_double_value_row) + with pytest.raises(ValueError, match="map cannot be combined"): + explicit(some_permutation.map(_double_value_row)) + + +def test_map_rejects_format_without_optional_dependency( + some_permutation: Permutation, monkeypatch +): + """Test the map check runs before a format imports an optional dependency.""" + import sys + + # Make polars fail to import, as it does on an install without extras + monkeypatch.setitem(sys.modules, "polars", None) + with pytest.raises(ValueError, match="map cannot be combined"): + some_permutation.map(_double_value_row).with_format("polars") + + +def test_map_rejects_explicit_transform_from_old_pickle( + some_permutation: Permutation, +): + """Test pickles written before explicit_transform existed keep the guard.""" + + def restore_without_flag(permutation): + state = permutation.__getstate__() + del state["explicit_transform"] + restored = Permutation.__new__(Permutation) + restored.__setstate__(state) + return restored + + with pytest.raises(ValueError, match="map cannot be combined"): + restore_without_flag(some_permutation.with_format("arrow")).map( + _double_value_row + ) + # The default transform is indistinguishable from an explicit "python" format + mapped = restore_without_flag(some_permutation).map(_double_value_row) + assert mapped.take_offsets([0]) == [ + _double_value_row(row) for row in some_permutation.take_offsets([0]) + ] + + +def test_map_rejects_transform_passed_to_constructor(some_table: Table): + """Test a transform given to the constructor counts as explicit too.""" + permutation = Permutation( + some_table, + None, + 0, + {"id": "id"}, + DEFAULT_BATCH_SIZE, + Transforms.arrow2arrow, + ) + with pytest.raises(ValueError, match="map cannot be combined"): + permutation.map(_double_value_row) + + +def test_map_take_offsets(some_permutation: Permutation): + """Test .map() keeps the positions and duplicates of the requested offsets.""" + calls = [] + + def record(batch): + calls.append(batch) + return batch + + mapped = some_permutation.map(_double_value_row).map(record, batched=True) + offsets = [5, 0, 5, 2] + expected = [ + _double_value_row(row) for row in some_permutation.take_offsets(offsets) + ] + assert mapped.take_offsets(offsets) == expected + assert mapped.__getitems__(offsets) == expected + + calls.clear() + assert mapped.take_offsets([]) == [] + assert calls == [] + + +def test_map_validates_output(some_permutation: Permutation): + """Test .map() rejects callback output that would break the batch shape.""" + with pytest.raises(ValueError, match="returned 1 values for column `id`"): + some_permutation.map( + lambda batch: {"id": batch["id"][:1]}, batched=True + ).take_offsets([0, 1]) + with pytest.raises(TypeError, match="must return a dict of columns, got list"): + some_permutation.map( + lambda batch: list(batch.values()), batched=True + ).take_offsets([0, 1]) + # A str has the right length here but is still not a column of values + for value in (2, "ab"): + with pytest.raises(TypeError, match="list of values for column `n`, got"): + some_permutation.map(lambda batch: {"n": value}, batched=True).take_offsets( + [0, 1] + ) + with pytest.raises( + TypeError, match="must return a dict for each row, got NoneType" + ): + some_permutation.map(lambda row: None).take_offsets([0, 1]) + with pytest.raises(ValueError, match="did not return the same keys for every row"): + some_permutation.map( + lambda row: row if row["id"] % 2 else {"id": row["id"]} + ).map(lambda batch: batch, batched=True).take_offsets(list(range(10))) + + +def test_map_projection_and_schema(some_permutation: Permutation): + """Test the selection and schema describe the read that feeds the callbacks.""" + + def to_str(row): + return {name: str(value) for name, value in row.items()} + + mapped = some_permutation.map(to_str) + assert mapped.schema == some_permutation.schema + assert mapped.column_names == ["id", "value"] + + for projected in ( + some_permutation.select_columns(["id"]).map(to_str), + mapped.select_columns(["id"]), + mapped.remove_columns(["value"]), + ): + assert projected.schema == some_permutation.select_columns(["id"]).schema + assert list(projected.take_offsets([0])[0]) == ["id"] + + renamed = mapped.rename_column("value", "data") + assert renamed.column_names == ["id", "data"] + assert list(renamed.take_offsets([0])[0]) == ["id", "data"] + + +def test_map_is_lazy(some_permutation: Permutation): + """Test .map() does not call fn until iteration.""" + call_count = [0] + + def counting_fn(row): + call_count[0] += 1 + return row + + mapped = some_permutation.map(counting_fn) + assert call_count[0] == 0 + + mapped.__getitems__([0]) + assert call_count[0] == 1 + + +def test_map_non_callable(some_permutation: Permutation): + """Test .map() raises TypeError for non-callable fn.""" + with pytest.raises(TypeError, match="fn must be callable"): + some_permutation.map("not a function") + + +@pytest.mark.parametrize( + "fn, batched", [(_double_value_row, False), (_double_value_batch, True)] +) +def test_map_pickle_round_trip(some_permutation: Permutation, fn, batched): + """Test a mapped permutation reads the same data after a pickle round trip.""" + import pickle + + mapped = some_permutation.map(fn, batched=batched) + restored = pickle.loads(pickle.dumps(mapped)) + + offsets = [3, 1, 3] + assert restored.take_offsets(offsets) == mapped.take_offsets(offsets) + assert restored.take_offsets(offsets)[0]["value"] == ( + some_permutation.take_offsets(offsets)[0]["value"] * 2 + ) + # The restored permutation keeps enforcing the map / format constraint + with pytest.raises(ValueError, match="map cannot be combined"): + restored.with_format("arrow") + explicit = pickle.loads(pickle.dumps(some_permutation.with_format("arrow"))) + with pytest.raises(ValueError, match="map cannot be combined"): + explicit.map(fn, batched=batched) diff --git a/python/python/tests/test_remote_db.py b/python/python/tests/test_remote_db.py index f8d264e31..5aae68a1c 100644 --- a/python/python/tests/test_remote_db.py +++ b/python/python/tests/test_remote_db.py @@ -3526,6 +3526,74 @@ def test_remote_create_rtree_index(): ] +@pytest.mark.asyncio +@pytest.mark.parametrize("use_async", [False, True]) +async def test_remote_scalar_plugin_nests_params(use_async): + from lancedb.index import ScalarPlugin + + received_requests = [] + + def handler(request): + request.send_response(200) + request.send_header("Content-Type", "application/json") + request.end_headers() + if request.path == "/v1/table/test/describe/": + fields = [{"name": "id", "type": {"type": "int32"}, "nullable": False}] + request.wfile.write( + json.dumps({"version": 1, "schema": {"fields": fields}}).encode() + ) + elif request.path == "/v1/table/test/create_index/": + received_requests.append(read_json_body(request)) + request.wfile.write(b"{}") + else: + raise AssertionError(f"Unexpected request: {request.path}") + + cases = [ + (ScalarPlugin(" ZoneMap "), {}), + ( + ScalarPlugin("bloomfilter", {"number_of_items": 4096, "column": "not_id"}), + {"name": "id_bloom", "replace": False}, + ), + (ScalarPlugin("bloomfilter", '{"probability": 0.01}'), {}), + (ScalarPlugin("zonemap", {}), {}), + ] + + if use_async: + async with mock_lancedb_connection_async(handler) as db: + table = await db.open_table("test") + for config, options in cases: + await table.create_index("id", config=config, **options) + else: + with mock_lancedb_connection(handler) as db: + table = db.open_table("test") + for config, options in cases: + table.create_index("id", config=config, **options) + + assert received_requests == [ + {"column": "id", "index_type": "PLUGIN", "plugin_type": "ZONEMAP"}, + { + "column": "id", + "index_type": "PLUGIN", + "plugin_type": "BLOOMFILTER", + "name": "id_bloom", + "replace": False, + "params": {"number_of_items": 4096, "column": "not_id"}, + }, + { + "column": "id", + "index_type": "PLUGIN", + "plugin_type": "BLOOMFILTER", + "params": {"probability": 0.01}, + }, + { + "column": "id", + "index_type": "PLUGIN", + "plugin_type": "ZONEMAP", + "params": {}, + }, + ] + + @pytest.mark.parametrize( "rq_kwargs", [{}, {"num_bits": None}, {"num_bits": 1}, {"num_bits": 4}] ) diff --git a/python/python/tests/test_torch.py b/python/python/tests/test_torch.py index e555bf7db..afbba92d1 100644 --- a/python/python/tests/test_torch.py +++ b/python/python/tests/test_torch.py @@ -631,6 +631,38 @@ def test_permutation_torch_dict_dataloader_spawn(tmp_db): assert sorted(seen) == list(range(11)) +def _map_add_scaled(row): + return {**row, "scaled": row["a"] * 2} + + +def _map_add_total(batch): + total = [a + scaled for a, scaled in zip(batch["a"], batch["scaled"])] + return {**batch, "total": total} + + +def test_permutation_map_dataloader_spawn(tmp_db): + """A map chain must be picklable so spawned DataLoader workers can run it.""" + table = tmp_db.create_table("test_table", pa.table({"a": range(100)})) + permutation = ( + Permutation.identity(table) + .map(_map_add_scaled) + .map(_map_add_total, batched=True) + ) + + dataloader = torch.utils.data.DataLoader( + permutation, + batch_size=10, + num_workers=1, + multiprocessing_context="spawn", + ) + seen = [] + for batch in dataloader: + assert set(batch) == {"a", "scaled", "total"} + assert torch.equal(batch["total"], batch["a"] * 3) + seen.extend(batch["a"].tolist()) + assert seen == list(range(100)) + + def test_batch_to_tensor_columns_zero_copy_and_slice_offsets(): vectors = [[float(i), float(i) + 0.5, float(i) + 1.0] for i in range(5)] nested_values = np.arange(5 * 3 * 2, dtype=np.float32).reshape(5, 3, 2) diff --git a/python/src/index.rs b/python/src/index.rs index ff75bb321..1941e3f10 100644 --- a/python/src/index.rs +++ b/python/src/index.rs @@ -7,10 +7,10 @@ use lancedb::index::vector::{ IvfPqIndexBuilder, IvfRqIndexBuilder, IvfSqIndexBuilder, }; use lancedb::index::{ - Index as LanceDbIndex, + Index as LanceDbIndex, IndexType, scalar::{ BTreeIndexBuilder, DocumentGranularity, FmIndexBuilder, FtsIndexBuilder, NGramIndexBuilder, - RTreeIndexBuilder, ZoneMapIndexBuilder, + PluginIndexBuilder, RTreeIndexBuilder, ZoneMapIndexBuilder, }, }; use pyo3::IntoPyObject; @@ -129,6 +129,15 @@ pub fn extract_index_params(source: &Option>) -> PyResult { + let params = source.extract::()?; + let invalid = |err: lancedb::Error| PyValueError::new_err(err.to_string()); + let mut builder = PluginIndexBuilder::new(params.index_type).map_err(invalid)?; + if let Some(json) = params.params_json { + builder = builder.params_json(json).map_err(invalid)?; + } + Ok(LanceDbIndex::Plugin(builder)) + } "FTS" => { let params = source.extract::()?; let code_options = CodeAnalyzerOptions { @@ -303,7 +312,7 @@ pub fn extract_index_params(source: &Option>) -> PyResult Err(PyValueError::new_err(format!( - "Invalid index type '{}'. Must be one of BTree, Bitmap, LabelList, Fm, NGram, ZoneMap, RTree, FTS, IvfPq, IvfSq, IvfHnswPq, IvfHnswSq, or IvfHnswFlat", + "Invalid index type '{}'. Must be one of BTree, Bitmap, LabelList, Fm, NGram, ZoneMap, RTree, ScalarPlugin, FTS, IvfPq, IvfSq, IvfHnswPq, IvfHnswSq, or IvfHnswFlat", not_supported ))), } @@ -312,6 +321,13 @@ pub fn extract_index_params(source: &Option>) -> PyResult, +} + #[derive(FromPyObject)] struct FtsParams { with_position: bool, @@ -554,7 +570,12 @@ fn parse_index_details(py: Python<'_>, s: String) -> Py { impl IndexConfig { pub fn from_lancedb(py: Python<'_>, value: lancedb::index::IndexConfig) -> Self { - let index_type = format!("{:?}", value.index_type); + // A registered plugin's type is its display name, such as "MinHashLsh", + // which `Debug` would render as `Custom("MinHashLsh")`. + let index_type = match value.index_type { + IndexType::Custom(name) => name, + index_type => format!("{index_type:?}"), + }; Self { index_type, columns: value.columns, diff --git a/python/uv.lock b/python/uv.lock index 73649f4d7..8555467dc 100644 --- a/python/uv.lock +++ b/python/uv.lock @@ -1,5 +1,5 @@ version = 1 -revision = 3 +revision = 5 requires-python = ">=3.11" resolution-markers = [ "python_full_version >= '3.14' and sys_platform == 'win32'", @@ -1813,7 +1813,7 @@ docs = [ { name = "mkdocs" }, { name = "mkdocs-jupyter" }, { name = "mkdocs-material" }, - { name = "mkdocstrings-python" }, + { name = "mkdocstrings", extra = ["python"] }, ] embeddings = [ { name = "awscli" }, @@ -1888,8 +1888,8 @@ requires-dist = [ { name = "maturin", marker = "extra == 'dev'", specifier = ">=1.10" }, { name = "mkdocs", marker = "extra == 'docs'" }, { name = "mkdocs-jupyter", marker = "extra == 'docs'" }, - { name = "mkdocs-material", marker = "extra == 'docs'" }, - { name = "mkdocstrings-python", marker = "extra == 'docs'" }, + { name = "mkdocs-material", marker = "extra == 'docs'", specifier = ">=9.8.2" }, + { name = "mkdocstrings", extras = ["python"], marker = "extra == 'docs'", specifier = ">=1.0.7,<2" }, { name = "numpy", specifier = ">=1.24.0" }, { name = "oci", marker = "extra == 'embeddings'", specifier = ">=2.165.1" }, { name = "ollama", marker = "extra == 'embeddings'", specifier = ">=0.3.0" }, @@ -1912,7 +1912,7 @@ requires-dist = [ { name = "pyarrow-stubs", marker = "extra == 'tests'", specifier = ">=16.0" }, { name = "pydantic", specifier = ">=2.7.4,<3" }, { name = "pylance", marker = "extra == 'pylance'", specifier = ">=15.0.0b3" }, - { name = "pylance", marker = "extra == 'tests'", specifier = "==15.0.0b32" }, + { name = "pylance", marker = "extra == 'tests'", specifier = "==15.0.0b34" }, { name = "pyright", marker = "extra == 'dev'", specifier = ">=1.1.350" }, { name = "pytest", marker = "extra == 'tests'", specifier = ">=7.0" }, { name = "pytest-asyncio", marker = "extra == 'tests'", specifier = ">=0.21" }, @@ -2182,7 +2182,7 @@ wheels = [ [[package]] name = "mkdocs-material" -version = "9.7.6" +version = "9.8.2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "babel" }, @@ -2197,9 +2197,9 @@ dependencies = [ { name = "pymdown-extensions" }, { name = "requests" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/45/29/6d2bcf41ae40802c4beda2432396fff97b8456fb496371d1bc7aad6512ec/mkdocs_material-9.7.6.tar.gz", hash = "sha256:00bdde50574f776d328b1862fe65daeaf581ec309bd150f7bff345a098c64a69", size = 4097959, upload-time = "2026-03-19T15:41:58.161Z" } +sdist = { url = "https://files.pythonhosted.org/packages/99/bf/c47389fa622b513c2d115eb4c16075ef04a5f4d8156039f46cb26e5c70a9/mkdocs_material-9.8.2.tar.gz", hash = "sha256:005d942bdbfa22efa049f4818c31d42fb36bed6d362adb641dd7a2e948078f9d", size = 4160697, upload-time = "2026-11-19T19:52:25.799Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/2c/01/bc663630c510822c95c47a66af9fa7a443c295b47d5f041e5e6ae62ef659/mkdocs_material-9.7.6-py3-none-any.whl", hash = "sha256:71b84353921b8ea1ba84fe11c50912cc512da8fe0881038fcc9a0761c0e635ba", size = 9305470, upload-time = "2026-03-19T15:41:55.217Z" }, + { url = "https://files.pythonhosted.org/packages/18/86/9204441dd9e224f1dc3f1a32edf6a474e84696bfa493c7df067dcde36366/mkdocs_material-9.8.2-py3-none-any.whl", hash = "sha256:ef1414cab33d64fcc13387e972af5ba4620f55f93482d1842933399ed2c69b02", size = 9302480, upload-time = "2026-11-19T19:52:22.436Z" }, ] [[package]] @@ -2213,7 +2213,7 @@ wheels = [ [[package]] name = "mkdocstrings" -version = "1.0.4" +version = "1.0.7" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "jinja2" }, @@ -2223,9 +2223,14 @@ dependencies = [ { name = "mkdocs-autorefs" }, { name = "pymdown-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/1d/5d/f888d4d3eb31359b327bc9b17a212d6ef03fe0b0682fbb3fc2cb849fb12b/mkdocstrings-1.0.4.tar.gz", hash = "sha256:3969a6515b77db65fd097b53c1b7aa4ae840bd71a2ee62a6a3e89503446d7172", size = 100088, upload-time = "2026-04-15T09:16:53.376Z" } +sdist = { url = "https://files.pythonhosted.org/packages/f5/e8/445b19834bf9559ebbbaa76897e965665b83d2861461eed8d8de4d122057/mkdocstrings-1.0.7.tar.gz", hash = "sha256:0951b147f352118a45a3db85f0f3b660833d34cb5120a2751315b8d08dafd159", size = 103739, upload-time = "2026-10-10T13:50:59.957Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/6e/94/be70f8ee9c45f2f62b39a1f0e9303bc20e138a8f3b8e50ffd89498e177e1/mkdocstrings-1.0.4-py3-none-any.whl", hash = "sha256:63464b4b29053514f32a1dbbf604e52876d5e638111b0c295ab7ed3cac73ca9b", size = 35560, upload-time = "2026-04-15T09:16:51.436Z" }, + { url = "https://files.pythonhosted.org/packages/22/c3/9062531735ff1fd27f3a79c353c4cf4d822eeffd062fd90b2c553a96f4bb/mkdocstrings-1.0.7-py3-none-any.whl", hash = "sha256:9563828667eeb35256f87a6b61fe857676ac628ec1abbce9aea9839a502c9cb1", size = 41597, upload-time = "2026-10-10T13:50:58.43Z" }, +] + +[package.optional-dependencies] +python = [ + { name = "mkdocstrings-python" }, ] [[package]] @@ -3644,20 +3649,20 @@ crypto = [ [[package]] name = "pylance" -version = "15.0.0b32" +version = "15.0.0b34" source = { registry = "https://pypi.fury.io/lance-format/" } dependencies = [ { name = "lance-namespace" }, { name = "pyarrow" }, ] wheels = [ - { url = "https://pypi.fury.io/lance-format/-/ver_1mmPD/pylance-15.0.0b32-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:1946f9559385773909c685fe46c474e988d4d283d78cab5bbcfa6f32769e8623" }, - { url = "https://pypi.fury.io/lance-format/-/ver_1fg8VI/pylance-15.0.0b32-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:3c5623245aa21700fe7377f9c25c15d87e3e38ea178eb315877a184352c6e399" }, - { url = "https://pypi.fury.io/lance-format/-/ver_1rf9nS/pylance-15.0.0b32-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:87e6b46d8c629fbf3d0383e5d515a95857bc8a5635c5d19d0b5e8a562b218ba6" }, - { url = "https://pypi.fury.io/lance-format/-/ver_176TqH/pylance-15.0.0b32-cp310-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:2cd78d8a4472f31d292bd8ccc530a83af8b3e11563898a9748d8404d12c12b03" }, - { url = "https://pypi.fury.io/lance-format/-/ver_1gbxKE/pylance-15.0.0b32-cp310-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:b6ebff00b80f00bd5c809b83a046981f9ba3f33bac8b347cc44b95ec235c16c0" }, - { url = "https://pypi.fury.io/lance-format/-/ver_qSF36/pylance-15.0.0b32-cp310-abi3-win_amd64.whl", hash = "sha256:5edc7d24a93e363186e0ffe561aa00eaeda7140cad26885043b378ffe64f10e0" }, - { url = "https://pypi.fury.io/lance-format/-/ver_JyVBF/pylance-15.0.0b32-cp310-abi3-win_arm64.whl", hash = "sha256:0d066b44acb0949b3f59eefe30092c982f9797dcb41423dd10fcd63210a2f06e" }, + { url = "https://pypi.fury.io/lance-format/-/ver_2c6cEN/pylance-15.0.0b34-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:a57e6864acf83fef3729ce51e27edf5a76179c308eb747ef0ec6cc51231ef968" }, + { url = "https://pypi.fury.io/lance-format/-/ver_oRvqr/pylance-15.0.0b34-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:6546b3631fcf8a1dd18b144c0d29fe152320b2e91c3a83ccdca2e3b36d66afb6" }, + { url = "https://pypi.fury.io/lance-format/-/ver_1uoRCM/pylance-15.0.0b34-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:2077fdfba60fb40db49b2afbb0c35a0fa1935977a7c3820007eef36f4bc758af" }, + { url = "https://pypi.fury.io/lance-format/-/ver_2auLpe/pylance-15.0.0b34-cp310-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:97a5a3d24388619eec61bee71589794517ff7df41fcfdaae2e56e5e8fb1da80d" }, + { url = "https://pypi.fury.io/lance-format/-/ver_1pf71p/pylance-15.0.0b34-cp310-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:b0f20b4957d81e0ca5461b3fbd27a37863124d4303a232925c25efab614449b2" }, + { url = "https://pypi.fury.io/lance-format/-/ver_1p6L6I/pylance-15.0.0b34-cp310-abi3-win_amd64.whl", hash = "sha256:780e85cfae25ae26c8eccd5dc40ae38003e8fe0752a5e5b4e124f14d8288bd87" }, + { url = "https://pypi.fury.io/lance-format/-/ver_9H5Qj/pylance-15.0.0b34-cp310-abi3-win_arm64.whl", hash = "sha256:05edaf5e3254ae798437bae276791fd311e110db86e62a002b2fa909b3f3b8cf" }, ] [[package]] diff --git a/release_process.md b/release_process.md index 55521774e..344993fb9 100644 --- a/release_process.md +++ b/release_process.md @@ -170,6 +170,30 @@ the publishing job replaces assets with matching names on an existing release. Verify beta releases remain marked as prereleases and do not take the latest release designation. +### Homebrew tap updates + +After a stable GitHub release publishes, the `homebrew` job reads its +`SHA256SUMS` and opens a PR against `lancedb/homebrew-tap`. Review the +version and three checksums, wait for the tap's install tests, then merge the +PR manually. Rerunning the failed job reuses the release-specific branch. + +Before enabling the job, land the initial `Formula/lancedb.rb` on the tap's +`main` branch and configure the release credentials: + +1. Register a private GitHub App under the LanceDB organization. Grant repository + permissions **Contents** and **Pull requests** (both read and write). Leave + webhooks disabled. Install the App on the selected repository + `lancedb/homebrew-tap`. +2. In `lancedb/lancedb`, create a GitHub Actions environment named + `homebrew-tap`. Under deployment branches and tags, select tags matching + `v*`. Add the App's **Client ID** as the environment variable + `HOMEBREW_TAP_APP_CLIENT_ID` and its generated PEM private key as the + environment secret `HOMEBREW_TAP_APP_PRIVATE_KEY`. + +The release job exchanges the key for a short-lived tap installation token. +If opening the tap PR fails, fix the configuration and rerun the failed job +against the already published release. + ## Breaking changes We try to avoid breaking changes, but sometimes they are necessary. When there diff --git a/rust/lancedb/Cargo.toml b/rust/lancedb/Cargo.toml index 508b5891c..b5251db76 100644 --- a/rust/lancedb/Cargo.toml +++ b/rust/lancedb/Cargo.toml @@ -46,7 +46,7 @@ lance-io = { workspace = true } lance-index = { workspace = true, features = ["tokenizer-jieba", "tokenizer-lindera"] } lance-table = { workspace = true } # Keep the upstream source for downstream SDKs, where workspace patches do not apply. -lance-linalg = { "version" = "=15.0.0-beta.32", "tag" = "v15.0.0-beta.32", "git" = "https://github.com/lance-format/lance.git" } +lance-linalg = { "version" = "=15.0.0-beta.34", "tag" = "v15.0.0-beta.34", "git" = "https://github.com/lance-format/lance.git" } lance-encoding = { workspace = true } lance-arrow = { workspace = true } lance-namespace = { workspace = true } diff --git a/rust/lancedb/src/index.rs b/rust/lancedb/src/index.rs index 91c941154..30dcee3df 100644 --- a/rust/lancedb/src/index.rs +++ b/rust/lancedb/src/index.rs @@ -16,7 +16,8 @@ use crate::{DistanceType, Error, Result, job::Job, table::BaseTable}; use self::{ scalar::{ BTreeIndexBuilder, BitmapIndexBuilder, BloomFilterIndexBuilder, FmIndexBuilder, - LabelListIndexBuilder, NGramIndexBuilder, RTreeIndexBuilder, ZoneMapIndexBuilder, + LabelListIndexBuilder, NGramIndexBuilder, PluginIndexBuilder, RTreeIndexBuilder, + ZoneMapIndexBuilder, }, vector::{ IvfHnswFlatIndexBuilder, IvfHnswPqIndexBuilder, IvfHnswSqIndexBuilder, IvfPqIndexBuilder, @@ -74,6 +75,24 @@ pub enum Index { /// Native creation requires the `geo` feature. RTree(RTreeIndexBuilder), + /// Configure a scalar index of a type recognized by a registered database plugin. + /// + /// Select the type by name and provide optional JSON parameters with + /// [`PluginIndexBuilder`]. Prefer a dedicated variant when one is available. + /// + /// ``` + /// use lancedb::index::{Index, scalar::PluginIndexBuilder}; + /// + /// # async fn create_zonemap(table: &lancedb::Table) -> lancedb::Result<()> { + /// table + /// .create_index(&["timestamp"], Index::Plugin(PluginIndexBuilder::new("zonemap")?)) + /// .execute() + /// .await?; + /// # Ok(()) + /// # } + /// ``` + Plugin(PluginIndexBuilder), + /// Full text search index using BM25. /// /// Supports strings, lists of strings, and `lance.json` logical fields diff --git a/rust/lancedb/src/index/scalar.rs b/rust/lancedb/src/index/scalar.rs index 2555c1439..709f9cb9b 100644 --- a/rust/lancedb/src/index/scalar.rs +++ b/rust/lancedb/src/index/scalar.rs @@ -204,6 +204,110 @@ impl RTreeIndexBuilder { } } +/// Configure a scalar index of a type recognized by a registered database plugin. +/// +/// Use this for index types without a dedicated builder. Prefer a dedicated +/// builder, such as [`ZoneMapIndexBuilder`] or [`BloomFilterIndexBuilder`], when +/// one is available. +/// +/// Index type names are case-insensitive. Surrounding whitespace is ignored. +/// Parameters are optional and, if given, must be a JSON object. They are passed +/// as given. Each plugin defines its parameters and defaults; refer to the +/// plugin's documentation for guidance. +/// +/// An unknown plugin name or invalid parameters cause index creation to fail. +/// +/// ``` +/// use lancedb::index::{Index, scalar::PluginIndexBuilder}; +/// use serde_json::json; +/// +/// # async fn create_plugin_index(table: &lancedb::Table) -> lancedb::Result<()> { +/// let bloom_filter = PluginIndexBuilder::new("bloomfilter")? +/// .params(json!({"number_of_items": 4096, "probability": 0.01}))?; +/// table +/// .create_index(&["id"], Index::Plugin(bloom_filter)) +/// .execute() +/// .await?; +/// # Ok(()) +/// # } +/// ``` +#[derive(Debug, Clone, PartialEq)] +pub struct PluginIndexBuilder { + pub(crate) index_type: String, + pub(crate) params: Option>, +} + +impl PluginIndexBuilder { + /// Select the scalar index type named `index_type`. + /// + /// The name is trimmed and lower-cased. Returns + /// [`Error::InvalidInput`](crate::Error::InvalidInput) if it is empty. + pub fn new(index_type: impl Into) -> crate::Result { + let index_type = index_type.into().trim().to_lowercase(); + if index_type.is_empty() { + return Err(crate::Error::InvalidInput { + message: "a scalar index plugin name must not be empty".into(), + }); + } + Ok(Self { + index_type, + params: None, + }) + } + + /// Set the index parameters, which must be a JSON object. + /// + /// Returns [`Error::InvalidInput`](crate::Error::InvalidInput) for any + /// other JSON value, including `null`. + pub fn params(mut self, params: serde_json::Value) -> crate::Result { + match params { + serde_json::Value::Object(params) => { + self.params = Some(params); + Ok(self) + } + other => Err(crate::Error::InvalidInput { + message: format!( + "scalar index plugin params must be a JSON object, got {}", + json_kind(&other) + ), + }), + } + } + + /// Set the index parameters from a JSON string, which must hold an object. + /// + /// Returns [`Error::InvalidInput`](crate::Error::InvalidInput) if the string + /// is not valid JSON or holds anything but an object. + pub fn params_json(self, params: impl AsRef) -> crate::Result { + let params = + serde_json::from_str(params.as_ref()).map_err(|e| crate::Error::InvalidInput { + message: format!("scalar index plugin params are not valid JSON: {e}"), + })?; + self.params(params) + } + + /// The index type name, trimmed and lower-cased. + pub fn index_type(&self) -> &str { + &self.index_type + } + + /// The index parameters, if set. + pub fn parameters(&self) -> Option<&serde_json::Map> { + self.params.as_ref() + } +} + +fn json_kind(value: &serde_json::Value) -> &'static str { + match value { + serde_json::Value::Null => "null", + serde_json::Value::Bool(_) => "a boolean", + serde_json::Value::Number(_) => "a number", + serde_json::Value::String(_) => "a string", + serde_json::Value::Array(_) => "an array", + serde_json::Value::Object(_) => "an object", + } +} + pub use lance_index::scalar::FullTextSearchQuery; pub use lance_index::scalar::InvertedIndexParams as FtsIndexBuilder; pub use lance_index::scalar::InvertedIndexParams; @@ -267,4 +371,66 @@ mod tests { } assert!(RTreeIndexBuilder::default().page_size(2).is_ok()); } + + #[test] + fn plugin_index_builder_normalizes_the_name() { + for name in ["zonemap", "ZoneMap", "ZONEMAP", " zonemap\t"] { + assert_eq!( + PluginIndexBuilder::new(name).unwrap().index_type(), + "zonemap" + ); + } + for name in ["", " ", "\n"] { + assert!(matches!( + PluginIndexBuilder::new(name), + Err(crate::Error::InvalidInput { .. }) + )); + } + } + + #[test] + fn plugin_index_builder_accepts_only_object_params() { + let builder = PluginIndexBuilder::new("bloomfilter").unwrap(); + assert_eq!(builder.parameters(), None); + + let expected = serde_json::json!({"number_of_items": 4096}); + let from_value = builder.clone().params(expected.clone()).unwrap(); + let from_json = builder + .clone() + .params_json(r#"{"number_of_items": 4096}"#) + .unwrap(); + assert_eq!(from_value, from_json); + assert_eq!(from_value.parameters(), Some(expected.as_object().unwrap())); + assert_eq!( + builder + .clone() + .params(serde_json::json!({})) + .unwrap() + .parameters(), + Some(&serde_json::Map::new()) + ); + + for (params, kind) in [ + (serde_json::Value::Null, "null"), + (serde_json::json!(true), "a boolean"), + (serde_json::json!(1), "a number"), + (serde_json::json!("x"), "a string"), + (serde_json::json!([1]), "an array"), + ] { + let json = params.to_string(); + for result in [ + builder.clone().params(params), + builder.clone().params_json(json), + ] { + let Err(crate::Error::InvalidInput { message }) = result else { + panic!("non-object params must be rejected"); + }; + assert!(message.ends_with(kind), "{message}"); + } + } + let Err(crate::Error::InvalidInput { message }) = builder.params_json("{not json") else { + panic!("malformed JSON must be rejected"); + }; + assert!(message.contains("not valid JSON"), "{message}"); + } } diff --git a/rust/lancedb/src/remote/sql.rs b/rust/lancedb/src/remote/sql.rs index b2ca5651f..68f53b10e 100644 --- a/rust/lancedb/src/remote/sql.rs +++ b/rust/lancedb/src/remote/sql.rs @@ -38,6 +38,7 @@ use crate::sql::{Query, QueryDescription, QueryHandle, QueryStatus}; mod function; pub(super) mod materialized_view; mod objects; +pub(super) mod receipt; mod secret; pub(super) use secret::SecretWriteOperation; mod stream; diff --git a/rust/lancedb/src/remote/sql/materialized_view.rs b/rust/lancedb/src/remote/sql/materialized_view.rs index eb29e62af..c87adc9ec 100644 --- a/rust/lancedb/src/remote/sql/materialized_view.rs +++ b/rust/lancedb/src/remote/sql/materialized_view.rs @@ -7,7 +7,7 @@ use arrow_array::{Array, RecordBatch, StringArray}; use futures::TryStreamExt; use super::SqlClient; -use crate::arrow::SendableRecordBatchStream; +use super::receipt::ReceiptRow; use crate::database::ExecuteQueryRequest; use crate::error::{Error, Result}; use crate::listing::{ListingOptions, ListingPage}; @@ -60,66 +60,38 @@ impl SqlClient { true, ) .await?; - let query = Arc::new(submitted.query); if !submitted.materialized_view_job_handle_supported { - return Ok(MaterializedViewJobSubmission::Query(query)); + return Ok(MaterializedViewJobSubmission::Query(Arc::new( + submitted.query, + ))); } - let mut reader: SendableRecordBatchStream = query.reader().await?; - let mut rows = 0; - let mut registry_job_id = None; - let mut already_exists = false; - while let Some(batch) = reader.try_next().await? { - rows += batch.num_rows(); - if rows > 1 { - return Err(Error::Runtime { - message: "materialized-view submission must return exactly one status row" - .into(), - }); - } - if let Some(column) = batch.column_by_name("status") { - let values = column - .as_any() - .downcast_ref::() - .ok_or_else(|| Error::Runtime { - message: "materialized-view submission status is not UTF-8".into(), - })?; - already_exists = - values.len() == 1 && !values.is_null(0) && values.value(0) == "already_exists"; - } - if let Some(column) = batch.column_by_name("job_id") { - let values = column - .as_any() - .downcast_ref::() - .ok_or_else(|| Error::Runtime { - message: "materialized-view submission job_id is not UTF-8".into(), - })?; - if values.null_count() != 0 { - return Err(Error::Runtime { - message: "materialized-view submission contains a null job_id".into(), - }); - } - if values.is_empty() { - continue; - } - let value = values.value(0); - if !value.is_empty() { - registry_job_id = Some(value.to_string()); - } - } - } - if rows != 1 { - return Err(Error::Runtime { + let row = ReceiptRow::read(&submitted.query) + .await? + .ok_or_else(|| Error::Runtime { message: "materialized-view submission must return exactly one status row".into(), - }); + })?; + let already_exists = if let Some(column) = row.column("status") { + let status = column + .as_any() + .downcast_ref::() + .ok_or_else(|| Error::Runtime { + message: "materialized-view submission status is not UTF-8".into(), + })?; + !status.is_null(0) && status.value(0) == "already_exists" + } else { + false + }; + match row.job_id()? { + Some(id) => Ok(MaterializedViewJobSubmission::Registry { + job_id: id.to_owned(), + }), + None if already_exists => Ok(MaterializedViewJobSubmission::AlreadyExists), + None => Err(Error::Runtime { + message: + "server acknowledged an early materialized-view handle but returned no job_id" + .into(), + }), } - if already_exists && registry_job_id.is_none() { - return Ok(MaterializedViewJobSubmission::AlreadyExists); - } - let job_id = registry_job_id.ok_or_else(|| Error::Runtime { - message: "server acknowledged an early materialized-view handle but returned no job_id" - .into(), - })?; - Ok(MaterializedViewJobSubmission::Registry { job_id }) } pub(in crate::remote) async fn describe_materialized_view( diff --git a/rust/lancedb/src/remote/sql/receipt.rs b/rust/lancedb/src/remote/sql/receipt.rs new file mode 100644 index 000000000..4f45292d5 --- /dev/null +++ b/rust/lancedb/src/remote/sql/receipt.rs @@ -0,0 +1,60 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +use arrow_array::{Array, ArrayRef, RecordBatch, StringArray}; +use futures::TryStreamExt; + +use crate::sql::Query; +use crate::{Error, Result}; + +/// The single row returned by a SQL job submission, after its stream completed successfully. +pub(in crate::remote) struct ReceiptRow(RecordBatch); + +impl ReceiptRow { + /// Empty batches carry no receipt data. Zero or multiple rows yield `None`. + pub(in crate::remote) async fn read(query: &Query) -> Result> { + let mut reader = query.reader().await?; + let mut receipt = None; + let mut rows = 0usize; + while let Some(batch) = reader.try_next().await? { + rows = rows.saturating_add(batch.num_rows()); + if rows == 1 && batch.num_rows() == 1 { + receipt = Some(Self(batch)); + } + } + Ok(receipt.filter(|_| rows == 1)) + } + + pub(in crate::remote) fn column(&self, name: &str) -> Option<&ArrayRef> { + self.0.column_by_name(name) + } + + /// An absent column or an empty string can represent a completed no-op. + /// Each command decides whether its receipt permits that outcome. + pub(in crate::remote) fn job_id(&self) -> Result> { + let Some(column) = self.column("job_id") else { + return Ok(None); + }; + let ids = column + .as_any() + .downcast_ref::() + .ok_or_else(|| Error::Runtime { + message: "SQL job receipt job_id is not UTF-8".into(), + })?; + if ids.is_null(0) { + return Err(Error::Runtime { + message: "SQL job receipt contains a null job_id".into(), + }); + } + let id = ids.value(0); + if id.is_empty() { + Ok(None) + } else if id.trim().is_empty() { + Err(Error::Runtime { + message: "SQL job receipt contains a blank job_id".into(), + }) + } else { + Ok(Some(id)) + } + } +} diff --git a/rust/lancedb/src/remote/sql_test.rs b/rust/lancedb/src/remote/sql_test.rs index 7d7ac2d4a..277ec16ae 100644 --- a/rust/lancedb/src/remote/sql_test.rs +++ b/rust/lancedb/src/remote/sql_test.rs @@ -150,6 +150,8 @@ struct TestSqlService { /// How many exchange responses have been dropped, finished or not. exchange_drops: Arc, result: RecordBatch, + result_tail: Vec>, + result_frames: Option>, large_result: RecordBatch, dictionary_result: RecordBatch, } @@ -330,6 +332,8 @@ impl Default for TestSqlService { prewarm_azure_supported: false, exchange_drops: Arc::new(AtomicUsize::new(0)), result, + result_tail: vec![], + result_frames: None, large_result, dictionary_result, } @@ -569,16 +573,28 @@ impl FlightService for TestSqlService { } (!empty).then_some(Ok(result)) }) - .filter_map(futures::future::ready); + .filter_map(futures::future::ready) + .chain( + futures::stream::iter(self.result_tail.clone()).then(|item| async { + // Let tonic flush the preceding batch before sending an error trailer. + if item.is_err() { + tokio::task::yield_now().await; + } + item.map_err(|status| FlightError::Tonic(Box::new(status))) + }), + ); let mut encoder = FlightDataEncoderBuilder::new().with_schema(schema); if large { encoder = encoder.with_max_flight_data_size(8 * 1024 * 1024); } - let stream = encoder.build(input).map_err(Status::from); + let stream = match &self.result_frames { + Some(frames) => futures::stream::iter(frames.clone()).map(Ok).boxed(), + None => encoder.build(input).map_err(Status::from).boxed(), + }; if let Some(initial) = initial { - Ok(self.adaptive_response(&initial.query, stream.boxed())) + Ok(self.adaptive_response(&initial.query, stream)) } else { - Ok(Response::new(stream.boxed())) + Ok(Response::new(stream)) } } @@ -711,6 +727,13 @@ impl FlightService for TestSqlService { } let rows = parameters.ok_or_else(|| Status::invalid_argument("exchange without parameters"))?; + let rows = self + .result_overrides + .lock() + .unwrap() + .get(&query) + .cloned() + .unwrap_or(rows); let schema = rows.schema(); let rest: BoxStream<'static, arrow_flight::error::Result> = if query == "SELECT exchange slow" { @@ -1465,6 +1488,96 @@ async fn remote_create_if_not_exists_accepts_a_completed_noop_without_a_registry } } +#[rstest::rstest] +#[case::submitted("submitted", " job-1 ", Ok(Some(" job-1 ")), Ok(Some(" job-1 ")))] +#[case::blank_id("submitted", " \t ", Err("blank job_id"), Err("blank job_id"))] +#[case::missing_id("submitted", "", Err("returned no job_id"), Err("returned no job_id"))] +#[case::already_exists("already_exists", "", Ok(None), Err("create-only already_exists"))] +#[case::malformed_noop("already_exists", " \t ", Err("blank job_id"), Err("blank job_id"))] +#[tokio::test] +async fn remote_materialized_view_receipt_with_empty_batches( + #[case] status: &str, + #[case] job_id: &str, + #[case] expected_create: std::result::Result, &str>, + #[case] expected_refresh: std::result::Result, &str>, +) { + let row = RecordBatch::try_from_iter([ + ( + "status", + Arc::new(StringArray::from(vec![status])) as ArrayRef, + ), + ( + "job_id", + Arc::new(StringArray::from(vec![job_id])) as ArrayRef, + ), + ]) + .unwrap(); + let empty = row.slice(0, 0); + // FlightDataEncoderBuilder skips zero-row batches. Encode them explicitly on the wire. + let frames = + arrow_flight::utils::batches_to_flight_data(&row.schema(), vec![empty.clone(), row, empty]) + .unwrap(); + let service = TestSqlService { + adaptive: true, + defer: true, + materialized_view_job_handle_supported: true, + result_frames: Some(frames), + ..Default::default() + }; + let statements = service.statements.clone(); + let (sql, shutdown) = start_sql_service(service, ClientConfig::default()).await; + let db = RemoteDatabase::new_mock(|r| -> http::Response { + panic!("unexpected HTTP request during create: {}", r.url()) + }) + .with_sql_client(sql.clone()); + let table = receipt_test_table(sql); + let create = db + .create_materialized_view_async(CreateMaterializedViewRequest { + name: "events".into(), + namespace_path: vec!["team".into()], + query: "SELECT * FROM people".into(), + exist_ok: true, + with_no_data: false, + auto_refresh_enabled: None, + auto_refresh_interval_seconds: None, + total_cpu_millis: None, + total_memory_bytes: None, + total_gpu_count: None, + gpu_class: None, + gpu_count: None, + }) + .await; + let refresh = table.refresh_materialized_view_async(None, false).await; + for (operation, actual, expected) in [ + ( + "CREATE", + create.as_ref().map(|job| job.id()), + expected_create, + ), + ( + "REFRESH", + refresh.as_ref().map(|job| job.id()), + expected_refresh, + ), + ] { + match expected { + Ok(id) => assert_eq!(actual.unwrap(), id, "{operation}"), + Err(message) => { + let err = actual.unwrap_err().to_string(); + assert!(err.contains(message), "{operation}: {err}"); + } + } + } + assert_eq!( + *statements.lock().unwrap(), + [ + r#"CREATE MATERIALIZED VIEW IF NOT EXISTS "events" AS SELECT * FROM people"#, + r#"REFRESH MATERIALIZED VIEW "events""#, + ] + ); + shutdown.send(()).unwrap(); +} + #[tokio::test] async fn remote_create_registry_handle_reopens_describes_and_cancels() { let service = TestSqlService { @@ -4563,6 +4676,188 @@ fn prewarm_result() -> RecordBatch { .unwrap() } +fn receipt_test_table( + sql: SqlClient, +) -> RemoteTable { + RemoteTable::new_with_sql_client( + client_with_handler(|r| -> http::Response { + panic!( + "unexpected HTTP request while reading a job receipt: {}", + r.url() + ) + }), + "analytics".into(), + "events".into(), + vec!["team".into()], + "team$events".into(), + Default::default(), + Some(sql), + ) +} + +#[tokio::test] +async fn remote_maintenance_job_receipts_require_one_row_and_a_complete_stream() { + let receipt = prewarm_result(); + let empty = receipt.slice(0, 0); + let with_ids = |ids: ArrayRef| { + let versions = arrow_array::UInt64Array::from(vec![42; ids.len()]); + RecordBatch::try_from_iter([ + ("job_id", ids), + ("table_version", Arc::new(versions) as ArrayRef), + ]) + .unwrap() + }; + let ids = |values: Vec>| with_ids(Arc::new(StringArray::from(values))); + let invalid = "inspect jobs before retrying"; + // All three commands receive the same wire response. + for (first, tail, expected) in [ + ( + empty.clone(), + vec![Ok(receipt.clone()), Ok(empty.clone())], + Ok("warming-job"), + ), + (ids(vec![Some(" id ")]), vec![], Ok(" id ")), + (empty, vec![], Err(invalid)), + (ids(vec![None]), vec![], Err(invalid)), + (ids(vec![Some("")]), vec![], Err(invalid)), + (ids(vec![Some(" \t ")]), vec![], Err(invalid)), + ( + with_ids(Arc::new(Int64Array::from(vec![7]))), + vec![], + Err(invalid), + ), + (receipt.project(&[1]).unwrap(), vec![], Err(invalid)), + (ids(vec![Some("one"), Some("two")]), vec![], Err(invalid)), + (receipt.clone(), vec![Ok(receipt.clone())], Err(invalid)), + ( + receipt, + vec![Err(Status::data_loss("receipt stream interrupted"))], + Err("receipt stream interrupted"), + ), + ] { + let service = TestSqlService { + adaptive: true, + result: first, + result_tail: tail, + ..Default::default() + }; + let statements = service.statements.clone(); + let (sql, shutdown) = start_sql_service(service, ClientConfig::default()).await; + let table = receipt_test_table(sql); + let compact = table.compact_async(Default::default()).await; + let prewarm = table.prewarm_data_async(Default::default()).await; + let cleanup = table.cleanup_async(Default::default()).await; + for (result, command) in [ + (compact.as_ref().map(|j| j.id()), "OPTIMIZE"), + (prewarm.as_ref().map(|j| j.id()), "PREWARM"), + (cleanup.as_ref().map(|j| j.id()), "VACUUM"), + ] { + match expected { + Ok(id) => assert_eq!(result.unwrap(), Some(id), "{command}"), + Err(message) => { + let error = result.unwrap_err().to_string(); + assert!(error.contains(message), "{command}: {error}"); + if message == invalid { + assert!(error.contains(command), "{error}"); + } + } + } + } + let commands: Vec<_> = statements + .lock() + .unwrap() + .iter() + .map(|sql| sql.split_whitespace().next().unwrap().to_owned()) + .collect(); + assert_eq!(commands, ["OPTIMIZE", "PREWARM", "VACUUM"]); + shutdown.send(()).unwrap(); + } +} + +#[tokio::test] +async fn remote_prewarm_receipt_requires_a_non_null_uint64_version() { + let id = prewarm_result().project(&[0]).unwrap(); + for version in [ + None, + Some(Arc::new(Int64Array::from(vec![42])) as ArrayRef), + Some(Arc::new(arrow_array::UInt64Array::from(vec![None])) as ArrayRef), + ] { + let result = match version { + None => id.clone(), + Some(version) => RecordBatch::try_from_iter([ + ("job_id", id.column(0).clone()), + ("table_version", version), + ]) + .unwrap(), + }; + let service = TestSqlService { + adaptive: true, + result, + ..Default::default() + }; + let statements = service.statements.clone(); + let (sql, shutdown) = start_sql_service(service, ClientConfig::default()).await; + let table = receipt_test_table(sql); + let error = table + .prewarm_data_async(Default::default()) + .await + .unwrap_err() + .to_string(); + assert!( + error.contains("table_version") && error.contains("inspect jobs before retrying"), + "{error}" + ); + assert_eq!(statements.lock().unwrap().len(), 1); + shutdown.send(()).unwrap(); + } +} + +#[tokio::test] +async fn remote_prewarm_accepts_a_receipt_for_a_bound_filter() { + let statement = r#"PREWARM WITH (branch = 'exp') AS SELECT * FROM "events" WHERE tag = $tag"#; + let parameters = RecordBatch::try_from_iter([( + "tag", + Arc::new(StringArray::from(vec!["train's data"])) as ArrayRef, + )]) + .unwrap(); + let service = TestSqlService { + adaptive: true, + ..Default::default() + }; + service + .result_overrides + .lock() + .unwrap() + .insert(statement.to_owned(), prewarm_result()); + let exchanges = service.exchanges.clone(); + let statements = service.statements.clone(); + let headers = service.headers.clone(); + let (sql, shutdown) = start_sql_service(service, ClientConfig::default()).await; + let table = receipt_test_table(sql).with_branch(Some("exp".into())); + let job = table + .prewarm_data_async( + crate::table::PrewarmDataOptions::new() + .filter("tag = $tag") + .parameters(parameters.clone()), + ) + .await + .unwrap(); + assert_eq!(job.id(), Some("warming-job")); + assert_eq!( + *exchanges.lock().unwrap(), + [(statement.to_owned(), Some(parameters))] + ); + assert!(statements.lock().unwrap().is_empty()); + assert!( + headers + .lock() + .unwrap() + .iter() + .all(|h| h.database == "analytics" && h.namespace_path == "team") + ); + shutdown.send(()).unwrap(); +} + #[tokio::test] async fn remote_prewarm_data_returns_the_durable_job_without_polling() { use crate::table::PrewarmDataOptions; diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index 3642fb950..fe81ca80a 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -9,10 +9,12 @@ mod optimize; mod prewarm; #[cfg(test)] mod profile_tests; +mod receipt; #[cfg(test)] mod write_tests; use self::insert::{RemoteWriteExec, WriteOp}; +use self::receipt::JobReceipt; use super::client::RequestResultExt; use super::client::{HttpSend, RestfulLanceDbClient, Sender}; use super::db::ServerVersion; @@ -842,6 +844,12 @@ impl RemoteTable { Index::NGram(p) => ("NGRAM", Some(to_json(p)?)), Index::BloomFilter(p) => ("BLOOM_FILTER", Some(to_json(p)?)), Index::RTree(p) => ("RTREE", Some(to_json(p)?)), + // Keep generic plugin requests distinct from built-in index handling. + // The plugin's params are nested below rather than flattened. + Index::Plugin(p) => { + body["plugin_type"] = p.index_type().to_uppercase().into(); + ("PLUGIN", None) + } Index::FTS(p) => { validate_fts_field(&field)?; let mut params = to_json(p)?; @@ -880,6 +888,14 @@ impl RemoteTable { body[key] = value.clone(); } } + // A plugin's params are arbitrary, so they go under a single `params` + // key. Flattened, they could overwrite request fields such as `column`, + // `name`, `replace` or `branch`. + if let Index::Plugin(plugin) = &index.index + && let Some(params) = plugin.parameters() + { + body["params"] = serde_json::Value::Object(params.clone()); + } self.apply_branch_body(&mut body); let request = request.json(&body); @@ -4301,25 +4317,15 @@ impl BaseTable for RemoteTable { message: "manual cleanup requires a Flight SQL endpoint and SQL VACUUM support" .into(), })?; - let query = client + let submission = client .execute(crate::database::ExecuteQueryRequest { query: statement, default_namespace_path: self.namespace.clone(), parameters: None, options: Default::default(), }) - .await - .map_err(cleanup::map_error)?; - let mut reader = query.reader().await.map_err(cleanup::map_error)?; - let mut batches = Vec::new(); - while let Some(batch) = reader.try_next().await.map_err(cleanup::map_error)? { - batches.push(batch); - } - let job_id = cleanup::receipt(&batches)?; - Ok(Job::new_typed(Box::new(RemoteJob::new( - self.client.clone(), - job_id, - )))) + .await; + JobReceipt::Cleanup.accept(submission, &self.client).await } async fn compact_async( @@ -4334,29 +4340,15 @@ impl BaseTable for RemoteTable { .ok_or_else(|| Error::NotSupported { message: "compaction jobs require a Flight SQL endpoint".into(), })?; - let query = client + let submission = client .execute(crate::database::ExecuteQueryRequest { query: statement, default_namespace_path: self.namespace.clone(), parameters: None, options: Default::default(), }) - .await - .map_err(optimize::map_optimize_error)?; - let mut reader = query.reader().await.map_err(optimize::map_optimize_error)?; - let mut batches = Vec::new(); - while let Some(batch) = reader - .try_next() - .await - .map_err(optimize::map_optimize_error)? - { - batches.push(batch); - } - let job_id = optimize::receipt(&batches)?; - Ok(Job::new_typed(Box::new(RemoteJob::new( - self.client.clone(), - job_id, - )))) + .await; + JobReceipt::Compact.accept(submission, &self.client).await } async fn add_columns( @@ -4986,26 +4978,15 @@ impl BaseTable for RemoteTable { message: "data prewarm requires a Flight SQL endpoint and SQL PREWARM support" .into(), })?; - let query = client + let submission = client .execute_prewarm(crate::database::ExecuteQueryRequest { query: statement, default_namespace_path: self.namespace.clone(), parameters: options.parameters, options: Default::default(), }) - .await - .map_err(prewarm::map_error)?; - let mut reader = query.reader().await.map_err(prewarm::map_error)?; - let mut batches = Vec::new(); - while let Some(batch) = reader.try_next().await.map_err(prewarm::map_error)? { - batches.push(batch); - } - let (job_id, _table_version) = prewarm::receipt(&batches)?; - // Construct lazily: submission must not require an HTTP status round trip. - Ok(Job::new_typed(Box::new(RemoteJob::new( - self.client.clone(), - job_id, - )))) + .await; + JobReceipt::Prewarm.accept(submission, &self.client).await } async fn explain_prewarm_data( @@ -9564,6 +9545,103 @@ mod tests { .unwrap(); } + /// Generic index requests use `PLUGIN` and a separate `plugin_type`. Params + /// stay nested so they cannot replace routing fields or request metadata. + #[tokio::test] + async fn test_create_plugin_index_nests_params() { + use crate::index::scalar::PluginIndexBuilder; + + let colliding_params = json!({ + "column": "not_a", + "name": "not_my_index", + "replace": true, + "index_type": "BTREE", + "plugin_type": "ZONEMAP", + "branch": "not_my_branch", + "keys": ["label", "confidence"], + }); + let cases = [ + ( + PluginIndexBuilder::new(" ZoneMap ").unwrap(), + None, + true, + json!({"column": "a", "index_type": "PLUGIN", "plugin_type": "ZONEMAP"}), + ), + ( + PluginIndexBuilder::new("BloomFilter") + .unwrap() + .params(json!({"number_of_items": 4096})) + .unwrap(), + None, + true, + json!({ + "column": "a", + "index_type": "PLUGIN", + "plugin_type": "BLOOMFILTER", + "params": {"number_of_items": 4096}, + }), + ), + ( + PluginIndexBuilder::new("listelement") + .unwrap() + .params(colliding_params.clone()) + .unwrap(), + Some("my_index"), + false, + json!({ + "column": "a", + "index_type": "PLUGIN", + "plugin_type": "LISTELEMENT", + "name": "my_index", + "replace": false, + "params": colliding_params, + }), + ), + ( + PluginIndexBuilder::new("zonemap") + .unwrap() + .params(json!({})) + .unwrap(), + None, + true, + json!({"column": "a", "index_type": "PLUGIN", "plugin_type": "ZONEMAP", "params": {}}), + ), + ]; + + for (plugin, name, replace, expected_body) in cases { + let table = Table::new_with_handler("my_table", move |request| { + assert_eq!(request.method(), "POST"); + match request.url().path() { + "/v1/table/my_table/describe/" => { + let schema = Schema::new(vec![Field::new("a", DataType::Int32, false)]); + http::Response::builder() + .status(200) + .body(describe_response(&schema)) + .unwrap() + } + "/v1/table/my_table/create_index/" => { + let body = request.body().unwrap().as_bytes().unwrap(); + let body: serde_json::Value = serde_json::from_slice(body).unwrap(); + assert_eq!(body, expected_body); + http::Response::builder() + .status(200) + .body("{}".to_string()) + .unwrap() + } + path => panic!("Unexpected path: {}", path), + } + }); + + let mut builder = table + .create_index(&["a"], Index::Plugin(plugin)) + .replace(replace); + if let Some(name) = name { + builder = builder.name(name.to_string()); + } + builder.execute().await.unwrap(); + } + } + #[tokio::test] async fn test_create_index_returns_job() { let describe_calls = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0)); diff --git a/rust/lancedb/src/remote/table/cleanup.rs b/rust/lancedb/src/remote/table/cleanup.rs index c20417742..f8d4535d3 100644 --- a/rust/lancedb/src/remote/table/cleanup.rs +++ b/rust/lancedb/src/remote/table/cleanup.rs @@ -40,27 +40,6 @@ pub(super) fn statement( Ok(sql) } -pub(super) fn receipt(batches: &[RecordBatch]) -> Result { - let invalid = || { - Error::Runtime { message: "VACUUM did not return a single nonempty job_id receipt; inspect jobs before retrying because cleanup may already have been submitted".into() } - }; - if batches.iter().map(RecordBatch::num_rows).sum::() != 1 { - return Err(invalid()); - } - let batch = batches - .iter() - .find(|batch| batch.num_rows() == 1) - .ok_or_else(invalid)?; - let ids = batch - .column_by_name("job_id") - .and_then(|array| array.as_any().downcast_ref::()) - .ok_or_else(invalid)?; - if ids.is_null(0) || ids.value(0).trim().is_empty() { - return Err(invalid()); - } - Ok(ids.value(0).to_string()) -} - pub(super) fn plan(batches: &[RecordBatch]) -> Result { let invalid = || { Error::Runtime { message: "EXPLAIN VACUUM did not return a valid versioned preview; a compatible EXPLAIN (FORMAT JSON) VACUUM server is required. No execution fallback was attempted".into() } @@ -170,35 +149,6 @@ mod tests { assert!(statement("t", None, &CleanupOptions::new().min_age_seconds(u64::MAX)).is_err()); } - #[test] - fn ambiguous_cleanup_receipts_never_become_query_handles() { - let batch = |values: Vec>| { - RecordBatch::try_from_iter([( - "job_id", - Arc::new(StringArray::from(values)) as arrow_array::ArrayRef, - )]) - .unwrap() - }; - for batches in [ - vec![], - vec![batch(vec![])], - vec![batch(vec![None])], - vec![batch(vec![Some("")])], - vec![batch(vec![Some("one"), Some("two")])], - ] { - assert!( - receipt(&batches) - .unwrap_err() - .to_string() - .contains("inspect jobs before retrying") - ); - } - assert_eq!( - receipt(&[batch(vec![]), batch(vec![Some("durable-job")])]).unwrap(), - "durable-job" - ); - } - #[test] fn cleanup_compatibility_preserves_permissions_and_transport_errors() { for (code, diagnostic, expected) in [ diff --git a/rust/lancedb/src/remote/table/optimize.rs b/rust/lancedb/src/remote/table/optimize.rs index 80d4d9639..e3b1a612c 100644 --- a/rust/lancedb/src/remote/table/optimize.rs +++ b/rust/lancedb/src/remote/table/optimize.rs @@ -23,30 +23,6 @@ pub(super) fn statement( Ok(sql) } -/// Submission can already have created work: reject ambiguous receipts without -/// retrying or confusing the SQL query's identity with the compaction job. -pub(super) fn receipt(batches: &[arrow_array::RecordBatch]) -> Result { - use arrow_array::{Array, StringArray}; - let invalid = || { - Error::Runtime { message: "OPTIMIZE did not return a single nonempty job_id receipt; inspect jobs before retrying because compaction may already have been submitted".into() } - }; - if batches.iter().map(|batch| batch.num_rows()).sum::() != 1 { - return Err(invalid()); - } - let batch = batches - .iter() - .find(|batch| batch.num_rows() == 1) - .ok_or_else(invalid)?; - let ids = batch - .column_by_name("job_id") - .and_then(|a| a.as_any().downcast_ref::()) - .ok_or_else(invalid)?; - if ids.is_null(0) || ids.value(0).is_empty() { - return Err(invalid()); - } - Ok(ids.value(0).into()) -} - pub(super) fn compaction_sql_options( options: &crate::table::optimize::CompactionOverrides, ) -> Result> { @@ -301,37 +277,3 @@ mod tests { } } } - -#[cfg(test)] -mod receipt_tests { - use super::*; - use arrow_array::{ArrayRef, RecordBatch, StringArray}; - use std::sync::Arc; - - #[test] - fn compaction_receipt_requires_one_unambiguous_registry_id() { - let batch = |ids: Vec>| { - RecordBatch::try_from_iter([("job_id", Arc::new(StringArray::from(ids)) as ArrayRef)]) - .unwrap() - }; - assert_eq!( - receipt(&[batch(vec![Some("compacting-job")])]).unwrap(), - "compacting-job" - ); - for batches in [ - vec![], - vec![batch(vec![])], - vec![batch(vec![None])], - vec![batch(vec![Some("")])], - vec![batch(vec![Some("a"), Some("b")])], - vec![batch(vec![Some("a")]), batch(vec![Some("b")])], - ] { - assert!( - receipt(&batches) - .unwrap_err() - .to_string() - .contains("inspect jobs before retrying") - ); - } - } -} diff --git a/rust/lancedb/src/remote/table/prewarm.rs b/rust/lancedb/src/remote/table/prewarm.rs index 4b6b2236f..09510109e 100644 --- a/rust/lancedb/src/remote/table/prewarm.rs +++ b/rust/lancedb/src/remote/table/prewarm.rs @@ -1,9 +1,9 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright The LanceDB Authors -//! SQL submission and receipt validation for data-cache prewarm jobs. +//! SQL submission and preview decoding for data-cache prewarm jobs. -use arrow_array::{Array, RecordBatch, StringArray, UInt64Array}; +use arrow_array::{Array, RecordBatch, StringArray}; use datafusion_sql::sqlparser::{dialect::GenericDialect, parser::Parser, tokenizer::Token}; use super::{quote_sql_identifier, quote_sql_string}; @@ -84,33 +84,6 @@ pub(super) fn statement( Ok(sql) } -pub(super) fn receipt(batches: &[RecordBatch]) -> Result<(String, u64)> { - let invalid = || { - Error::Runtime { - message: "PREWARM did not return a single (job_id, table_version) receipt; inspect jobs before retrying because work may already have been submitted".into(), - } - }; - if batches.iter().map(RecordBatch::num_rows).sum::() != 1 { - return Err(invalid()); - } - let batch = batches - .iter() - .find(|batch| batch.num_rows() == 1) - .ok_or_else(invalid)?; - let id = batch - .column_by_name("job_id") - .and_then(|array| array.as_any().downcast_ref::()) - .ok_or_else(invalid)?; - let version = batch - .column_by_name("table_version") - .and_then(|array| array.as_any().downcast_ref::()) - .ok_or_else(invalid)?; - if id.is_null(0) || id.value(0).is_empty() || version.is_null(0) { - return Err(invalid()); - } - Ok((id.value(0).into(), version.value(0))) -} - /// Decode the versioned JSON payload without depending on the display text. pub(super) fn plan(batches: &[RecordBatch]) -> Result { let invalid = || { @@ -219,7 +192,6 @@ pub(super) fn map_error(error: Error) -> Error { #[cfg(test)] mod tests { use super::*; - use arrow_schema::{DataType, Field, Schema}; use std::sync::Arc; #[test] @@ -357,46 +329,6 @@ mod tests { } } - fn batch(ids: Vec>, versions: Vec>) -> RecordBatch { - RecordBatch::try_from_iter([ - ( - "job_id", - Arc::new(StringArray::from(ids)) as arrow_array::ArrayRef, - ), - ( - "table_version", - Arc::new(UInt64Array::from(versions)) as arrow_array::ArrayRef, - ), - ]) - .unwrap() - } - - #[test] - fn receipt_requires_one_non_null_job_and_version() { - assert_eq!( - receipt(&[batch(vec![Some("job-1")], vec![Some(42)])]).unwrap(), - ("job-1".into(), 42) - ); - for batches in [ - vec![], - vec![batch(vec![], vec![])], - vec![batch(vec![None], vec![Some(42)])], - vec![batch(vec![Some("")], vec![Some(42)])], - vec![batch(vec![Some("job")], vec![None])], - vec![batch(vec![Some("a"), Some("b")], vec![Some(1), Some(2)])], - vec![ - batch(vec![Some("a")], vec![Some(1)]), - batch(vec![Some("b")], vec![Some(2)]), - ], - vec![RecordBatch::new_empty(Arc::new(Schema::new(vec![ - Field::new("wrong", DataType::Utf8, false), - ])))], - ] { - let error = receipt(&batches).unwrap_err().to_string(); - assert!(error.contains("inspect jobs before retrying"), "{error}"); - } - } - #[test] fn compatibility_errors_preserve_permission_and_predicate_diagnostics() { for (code, message, unsupported) in [ diff --git a/rust/lancedb/src/remote/table/receipt.rs b/rust/lancedb/src/remote/table/receipt.rs new file mode 100644 index 000000000..818302cd7 --- /dev/null +++ b/rust/lancedb/src/remote/table/receipt.rs @@ -0,0 +1,71 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +use arrow_array::{Array, UInt64Array}; +use serde::de::DeserializeOwned; + +use super::{cleanup, optimize, prewarm}; +use crate::job::Job; +use crate::remote::client::{HttpSend, RestfulLanceDbClient}; +use crate::remote::job::RemoteJob; +use crate::remote::sql::receipt::ReceiptRow; +use crate::sql::Query; +use crate::{Error, Result}; + +#[derive(Clone, Copy)] +pub(super) enum JobReceipt { + Compact, + Prewarm, + Cleanup, +} + +impl JobReceipt { + fn invalid(self) -> Error { + let receipt = match self { + Self::Compact => "OPTIMIZE did not return a single nonempty job_id receipt", + Self::Prewarm => "PREWARM did not return a single (job_id, table_version) receipt", + Self::Cleanup => "VACUUM did not return a single nonempty job_id receipt", + }; + Error::Runtime { + message: format!( + "{receipt}; inspect jobs before retrying because work may already have been submitted" + ), + } + } + + /// A registry job can already be running when its SQL response is lost. + /// Only construct the handle after reading one valid row and the end of the stream. + pub(super) async fn accept( + self, + submission: Result, + client: &RestfulLanceDbClient, + ) -> Result> + where + T: Clone + DeserializeOwned + Send + Sync + 'static, + S: HttpSend, + { + let map_error = match self { + Self::Compact => optimize::map_optimize_error, + Self::Prewarm => prewarm::map_error, + Self::Cleanup => cleanup::map_error, + }; + let query = submission.map_err(map_error)?; + let row = ReceiptRow::read(&query) + .await + .map_err(map_error)? + .ok_or_else(|| self.invalid())?; + let Ok(Some(job_id)) = row.job_id() else { + return Err(self.invalid()); + }; + if matches!(self, Self::Prewarm) { + row.column("table_version") + .and_then(|column| column.as_any().downcast_ref::()) + .filter(|versions| !versions.is_null(0)) + .ok_or_else(|| self.invalid())?; + } + Ok(Job::new_typed(Box::new(RemoteJob::new( + client.clone(), + job_id.to_owned(), + )))) + } +} diff --git a/rust/lancedb/src/table/create_index.rs b/rust/lancedb/src/table/create_index.rs index a694cde68..79d7ed198 100644 --- a/rust/lancedb/src/table/create_index.rs +++ b/rust/lancedb/src/table/create_index.rs @@ -366,6 +366,15 @@ impl NativeTable { ScalarIndexParams::for_builtin(BuiltinIndexType::RTree).with_params(¶ms), )) } + // Lance resolves the plugin by name and the plugin checks the column + // and the parameters, so there is nothing to validate here. + Index::Plugin(plugin) => { + let mut params = ScalarIndexParams::new(plugin.index_type); + params.params = plugin + .params + .map(|params| serde_json::Value::Object(params).to_string()); + Ok(Box::new(params)) + } Index::FTS(fts_opts) => { validate_fts_field(field)?; Ok(Box::new(fts_opts)) @@ -532,6 +541,7 @@ impl NativeTable { Index::NGram(_) => IndexType::NGram, Index::BloomFilter(_) => IndexType::BloomFilter, Index::RTree(_) => IndexType::RTree, + Index::Plugin(_) => IndexType::Scalar, Index::FTS(_) => IndexType::Inverted, Index::IvfFlat(_) | Index::IvfSq(_) @@ -1850,6 +1860,191 @@ mod tests { } } + /// Lance's built-in plugins, created by name through the generic path, are + /// listed with the same type as their dedicated builders and serve filters. + #[tokio::test] + async fn test_create_plugin_index() { + use crate::index::IndexType; + use crate::index::scalar::PluginIndexBuilder; + + for (name, params, column, index_type, predicate, expected_rows) in [ + ( + "ZoneMap", + None, + "id", + IndexType::ZoneMap, + "id >= 2 AND id < 4", + 2, + ), + ( + "bloomfilter", + Some(serde_json::json!({"number_of_items": 2, "probability": 0.01})), + "text", + IndexType::BloomFilter, + "text = 'abc'", + 1, + ), + ("BTREE", None, "id", IndexType::BTree, "id = 3", 1), + ] { + let conn = connect("memory://").execute().await.unwrap(); + let batch = record_batch!( + ("id", Int32, [1, 2, 3, 4]), + ("text", Utf8, [Some("abc"), Some("xyz"), None, Some("")]) + ) + .unwrap(); + let table = conn.create_table("plugin", batch).execute().await.unwrap(); + + let mut plugin = PluginIndexBuilder::new(name).unwrap(); + if let Some(params) = params.clone() { + plugin = plugin.params(params).unwrap(); + } + table + .create_index(&[column], Index::Plugin(plugin)) + .name("plugin_idx".into()) + .execute() + .await + .unwrap(); + + let indices = table.list_indices().await.unwrap(); + assert_eq!(indices.len(), 1); + assert_eq!(indices[0].index_type, index_type, "{name}"); + assert_eq!(indices[0].columns, [column]); + let stats = table.index_stats("plugin_idx").await.unwrap().unwrap(); + assert_eq!(stats.index_type, index_type); + assert_eq!(stats.num_indexed_rows, 4); + + // Lance trained the plugin with the given params, not its defaults. + if let Some(params) = params { + let dataset = table.as_native().unwrap().dataset.get().await.unwrap(); + let stats: serde_json::Value = + serde_json::from_str(&dataset.index_statistics("plugin_idx").await.unwrap()) + .unwrap(); + for (key, value) in params.as_object().unwrap() { + assert_eq!(&stats["indices"][0][key], value, "{key}"); + } + } + + let query = table.query().only_if(predicate); + let plan = query.explain_plan(false).await.unwrap(); + assert!(plan.contains("ScalarIndexQuery"), "{name}: {plan}"); + let batches = query + .execute() + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + assert_eq!( + batches.iter().map(RecordBatch::num_rows).sum::(), + expected_rows, + "{name}" + ); + } + } + + /// A plugin LanceDB has no type for is listed as `Custom` with the name + /// the plugin reports. + #[tokio::test] + async fn test_create_plugin_index_without_lancedb_type_is_listed_as_custom() { + use crate::index::IndexType; + use crate::index::scalar::PluginIndexBuilder; + + let conn = connect("memory://").execute().await.unwrap(); + let batch = record_batch!(( + "value", + Utf8, + ["alpha beta", "beta gamma", "gamma delta", "delta alpha"] + )) + .unwrap(); + let table = conn.create_table("custom", batch).execute().await.unwrap(); + table + .create_index( + &["value"], + Index::Plugin(PluginIndexBuilder::new("MinHashLSH").unwrap()), + ) + .execute() + .await + .unwrap(); + + let indices = table.list_indices().await.unwrap(); + assert_eq!(indices.len(), 1); + assert_eq!( + indices[0].index_type, + IndexType::Custom("MinHashLsh".into()) + ); + assert_eq!(indices[0].index_type.to_string(), "MinHashLsh"); + assert_eq!(indices[0].columns, ["value"]); + } + + /// Lance's errors for an unknown plugin, a column the plugin cannot index + /// and params the plugin rejects reach the caller, through both execute + /// paths, and leave no index behind. + #[tokio::test] + async fn test_create_plugin_index_errors() { + use crate::index::scalar::PluginIndexBuilder; + + let conn = connect("memory://").execute().await.unwrap(); + let batch = + record_batch!(("id", Int32, [1, 2, 3]), ("text", Utf8, ["a", "b", "c"])).unwrap(); + let table = conn.create_table("errors", batch).execute().await.unwrap(); + + let plugin = |name: &str| PluginIndexBuilder::new(name).unwrap(); + for (column, index, expected) in [ + ( + "id", + plugin("NoSuchPlugin"), + "No scalar index plugin found for name 'nosuchplugin'", + ), + ("id", plugin("ngram"), "ngram"), + ( + "text", + plugin("bloomfilter") + .params(serde_json::json!({"number_of_items": "many"})) + .unwrap(), + "invalid type: string \"many\", expected u64", + ), + ] { + let error = table + .create_index(&[column], Index::Plugin(index.clone())) + .execute() + .await + .unwrap_err(); + assert!( + error + .to_string() + .to_lowercase() + .contains(&expected.to_lowercase()), + "{error}" + ); + + let error = table + .create_index(&[column], Index::Plugin(index)) + .execute_async() + .await + .unwrap() + .wait() + .await + .unwrap_err(); + assert!( + error + .to_string() + .to_lowercase() + .contains(&expected.to_lowercase()), + "{error}" + ); + } + assert!(table.list_indices().await.unwrap().is_empty()); + + // A missing column is still caught before any build starts. + assert!( + table + .create_index(&["missing"], Index::Plugin(plugin("zonemap"))) + .execute_async() + .await + .is_err() + ); + } + #[cfg(feature = "geo")] #[tokio::test] async fn test_create_rtree_index() { diff --git a/rust/lancedb/vendor/lance-linalg/Cargo.toml b/rust/lancedb/vendor/lance-linalg/Cargo.toml index e1c30f82f..d45e75d2e 100644 --- a/rust/lancedb/vendor/lance-linalg/Cargo.toml +++ b/rust/lancedb/vendor/lance-linalg/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lance-linalg" -version = "15.0.0-beta.32" +version = "15.0.0-beta.34" publish = false edition = { workspace = true } license = { workspace = true } diff --git a/rust/lancedb/vendor/lance-linalg/README.lancedb.md b/rust/lancedb/vendor/lance-linalg/README.lancedb.md index cf04d3813..bcd37f10b 100644 --- a/rust/lancedb/vendor/lance-linalg/README.lancedb.md +++ b/rust/lancedb/vendor/lance-linalg/README.lancedb.md @@ -1,5 +1,5 @@ -This directory contains `rust/lance-linalg` from Lance tag `v15.0.0-beta.32` -(commit `1115237a5eca8372494ef2d9c6d7886455cb51a6`), licensed under Apache-2.0. +This directory contains `rust/lance-linalg` from Lance tag `v15.0.0-beta.34` +(commit `abf5c3334780ad007f63b7402655cd1c311c6beb`), licensed under Apache-2.0. LanceDB patches `src/distance/cosine.rs` to recompute FLOAT32 cosine distances in FLOAT64 when squared norms or dot products overflow or underflow. Ordinary