mirror of
https://github.com/lancedb/lancedb.git
synced 2026-11-26 12:33:59 +00:00
Merge main into gatekeeper/fix-5025-1
This commit is contained in:
@@ -10,7 +10,7 @@ come from the `LanceDB.zip` asset of `lancedb/docs` release
|
||||
The product-terminology rules were added here: `EmbeddedName`,
|
||||
`RemoteExecution`, `OSSProduct`, `InternalNames`
|
||||
(warnings) and `LegacyCloud` (suggestion). They enforce the names in the
|
||||
docs repository's `STYLE.md#names`. Run every rule's tests from
|
||||
[style guide](../../docs/STYLE.md#names). Run every rule's tests from
|
||||
`.github/vale` with `vale test --coverage styles`.
|
||||
|
||||
Keeping the rules here lets contributors and CI run Vale without access to the
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
extends: existence
|
||||
message: "Avoid '%s' in prose. Use a comma, a colon, parentheses or two sentences."
|
||||
link: https://github.com/lancedb/docs/blob/main/STYLE.md#punctuation
|
||||
link: https://github.com/lancedb/lancedb/blob/main/docs/STYLE.md#punctuation
|
||||
level: warning
|
||||
nonword: true
|
||||
# An em dash in prose, and a double hyphen or en dash used as one, with a
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
extends: substitution
|
||||
message: "Use '%s' instead of '%s'."
|
||||
link: https://github.com/lancedb/docs/blob/main/STYLE.md#names
|
||||
link: https://github.com/lancedb/lancedb/blob/main/docs/STYLE.md#names
|
||||
level: warning
|
||||
ignorecase: false
|
||||
# The in-process execution model is LanceDB Embedded, whether the data is on
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
extends: substitution
|
||||
message: "Use '%s' instead of the internal name '%s'."
|
||||
link: https://github.com/lancedb/docs/blob/main/STYLE.md#names
|
||||
link: https://github.com/lancedb/lancedb/blob/main/docs/STYLE.md#names
|
||||
level: warning
|
||||
ignorecase: false
|
||||
# Internal component names stay out of public text. Environment variables such
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
extends: existence
|
||||
message: "'%s' is the legacy hosted service. Unless the text is specific to it, write 'LanceDB Enterprise'."
|
||||
link: https://github.com/lancedb/docs/blob/main/STYLE.md#names
|
||||
link: https://github.com/lancedb/lancedb/blob/main/docs/STYLE.md#names
|
||||
level: suggestion
|
||||
ignorecase: false
|
||||
# A suggestion, because `db://` URIs, `api_key` and `region` for the hosted
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
extends: existence
|
||||
message: "Avoid '%s'. OSS is not a product name: write 'LanceDB Embedded', or 'open source' as a property."
|
||||
link: https://github.com/lancedb/docs/blob/main/STYLE.md#names
|
||||
link: https://github.com/lancedb/lancedb/blob/main/docs/STYLE.md#names
|
||||
level: warning
|
||||
ignorecase: false
|
||||
# Bare OSS used as a product, as in "OSS and Enterprise" or "in OSS". "LanceDB
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
extends: substitution
|
||||
message: "Consider '%s' instead of '%s'."
|
||||
link: https://github.com/lancedb/docs/blob/main/STYLE.md#say-it-directly
|
||||
link: https://github.com/lancedb/lancedb/blob/main/docs/STYLE.md#say-it-directly
|
||||
level: suggestion
|
||||
ignorecase: true
|
||||
# Keep this list small. Technical nouns such as GPU utilization stay intact.
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
extends: substitution
|
||||
message: "Use '%s' instead of '%s'."
|
||||
link: https://github.com/lancedb/docs/blob/main/STYLE.md#names
|
||||
link: https://github.com/lancedb/lancedb/blob/main/docs/STYLE.md#names
|
||||
level: warning
|
||||
ignorecase: false
|
||||
# Case-sensitive. A lowercase package, repository or domain name, such as
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
extends: existence
|
||||
message: "Avoid '%s'. Write 'LanceDB Enterprise' and describe where the operation runs directly."
|
||||
link: https://github.com/lancedb/docs/blob/main/STYLE.md#names
|
||||
link: https://github.com/lancedb/lancedb/blob/main/docs/STYLE.md#names
|
||||
level: warning
|
||||
ignorecase: false
|
||||
# Remote storage, remote URLs and a git remote are other things and stay. Class
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
extends: existence
|
||||
message: "'%s' doesn't say what the section covers. Name the task or topic instead."
|
||||
link: https://github.com/lancedb/docs/blob/main/STYLE.md#headings
|
||||
link: https://github.com/lancedb/lancedb/blob/main/docs/STYLE.md#headings
|
||||
level: suggestion
|
||||
scope: heading
|
||||
ignorecase: true
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
extends: existence
|
||||
message: "'%s' talks about the writing, not the subject. State the point directly."
|
||||
link: https://github.com/lancedb/docs/blob/main/STYLE.md#say-it-directly
|
||||
link: https://github.com/lancedb/lancedb/blob/main/docs/STYLE.md#say-it-directly
|
||||
level: suggestion
|
||||
ignorecase: false
|
||||
scope: sentence
|
||||
|
||||
@@ -1,6 +1,12 @@
|
||||
LanceDB is a database designed for retrieval, including vector, full-text, and hybrid search.
|
||||
It is a wrapper around Lance. There are two backends: local (in-process like SQLite) and
|
||||
remote (against LanceDB Cloud).
|
||||
It is a wrapper around Lance. There are two editions: LanceDB Embedded (in-process, like
|
||||
SQLite) and LanceDB Enterprise (a server cluster reached over HTTP).
|
||||
|
||||
In user-facing text (docs, docstrings, error messages, examples), always say "Embedded"
|
||||
and "Enterprise". Don't say "local" or "remote" tables. ("LanceDB Cloud" means only the
|
||||
legacy hosted service, not Enterprise.) The code implements Enterprise in the `remote`
|
||||
module, the `remote` cargo feature, and `Remote*` types. Those names are internal and
|
||||
shouldn't leak into user-facing text.
|
||||
|
||||
The core of LanceDB is written in Rust. There are bindings in Python, Typescript, and Java.
|
||||
|
||||
@@ -72,9 +78,10 @@ back and fix it immediately if it is not conventional.
|
||||
## Example plan: adding a new method on Table
|
||||
|
||||
Adding a new method involves first adding it to the Rust core, then exposing it
|
||||
in the Python and TypeScript bindings. There are both local and remote tables.
|
||||
Remote tables are implemented via a HTTP API and require the `remote` cargo
|
||||
feature flag to be enabled. Python has both sync and async methods.
|
||||
in the Python and TypeScript bindings. Every method needs an Embedded and an
|
||||
Enterprise implementation. Enterprise tables are implemented via a HTTP API in the
|
||||
`remote` module and require the `remote` cargo feature flag to be enabled. Python
|
||||
has both sync and async methods.
|
||||
|
||||
Rust core changes:
|
||||
|
||||
@@ -104,7 +111,7 @@ TypeScript bindings changes:
|
||||
2. Run `pnpm build` to generate TypeScript definitions.
|
||||
3. Add typescript method on abstract class `Table` in `nodejs/lancedb/table.ts`.
|
||||
4. Add concrete method on `LocalTable` class in `nodejs/lancedb/table.ts`.
|
||||
* Note: despite the name, this class is also used for remote tables.
|
||||
* Note: despite the name, this class is also used for Enterprise tables.
|
||||
5. Add test in `nodejs/__test__/table.test.ts`.
|
||||
6. Run `pnpm run docs` to generate TypeScript documentation.
|
||||
|
||||
@@ -155,3 +162,17 @@ Please consider the following when reviewing code contributions.
|
||||
### Documentation
|
||||
* New features must include updates to the rust documentation comments. Link to
|
||||
relevant structs and methods to increase the value of documentation.
|
||||
* User guides (`docs/web`) are evergreen: document only the current API. Don't add
|
||||
migration tables or deprecation notices there. Mark deprecated APIs in their
|
||||
docstrings, which feed the API reference.
|
||||
|
||||
### Breaking changes and deprecation
|
||||
* Prefer deprecating over removing a released public API. When the new name differs
|
||||
from the old one, keep the old one as a deprecated alias (`#[deprecated]` in Rust,
|
||||
`DeprecationWarning` in Python, `@deprecated` in TypeScript), with a test that it
|
||||
still works.
|
||||
* Don't reuse a released public name for something with a different meaning. Callers
|
||||
get a confusing error instead of a deprecation warning.
|
||||
* For a breaking change, add `!` to the PR title and start the PR body with a
|
||||
`BREAKING CHANGE:` paragraph covering the new behavior, the old behavior, and how to
|
||||
migrate. Release notes are generated from it.
|
||||
|
||||
+23
-8
@@ -109,12 +109,13 @@ npm i -g mint@4.2.888
|
||||
|
||||
This previews this checkout, including your uncommitted changes. It doesn't
|
||||
include the other documentation sources or render the availability labels.
|
||||
Use the [combined preview](https://github.com/lancedb/docs#development) when
|
||||
checking Enterprise replacements or links to pages from another source.
|
||||
Checking Enterprise replacements or links to pages from another source needs
|
||||
the combined site, which maintainers build. Ask for that check in your pull
|
||||
request if your change needs it.
|
||||
Staging shows saved release editions, so it won't show a new source change
|
||||
just because that change merged.
|
||||
|
||||
Follow the [style guide](https://github.com/lancedb/docs/blob/main/STYLE.md).
|
||||
Follow the [style guide](docs/STYLE.md).
|
||||
[Vale](https://vale.sh) checks wording, names and punctuation using the
|
||||
[bundled LanceDB rules](.github/vale/README.md). Pull requests show suggestions
|
||||
on the lines they change. With Vale 3.24.0 installed, check a page locally with:
|
||||
@@ -182,15 +183,29 @@ You don't need to hold a documentation PR until launch. Use these controls:
|
||||
comment below the table or list, not between entries.
|
||||
|
||||
Drafts remain in the source. Use them to avoid advertising an unfinished
|
||||
feature, not to keep information confidential. See
|
||||
[Writing docs before release](https://github.com/lancedb/docs#writing-docs-before-release)
|
||||
for examples and how to preview a draft.
|
||||
feature, not to keep information confidential. A draft section looks like
|
||||
this:
|
||||
|
||||
```mdx
|
||||
{/*
|
||||
Draft for the Feature X release.
|
||||
|
||||
## Feature X {#feature-x}
|
||||
|
||||
Feature X does ...
|
||||
*/}
|
||||
```
|
||||
|
||||
Give the comment lines of its own, with a blank line before and after it. To
|
||||
see how a draft renders, remove its comment or its `.mintignore` entry in a
|
||||
local change you don't commit, then run `mint dev`.
|
||||
|
||||
Before the intended release, remove the draft controls, restore the navigation
|
||||
and links, and check the result. Those changes must be in the source commit the
|
||||
edition uses. A later change to `main` doesn't update an edition already saved.
|
||||
For a mistake in an existing edition, fix the source and request a
|
||||
[recorded correction](https://github.com/lancedb/docs#correcting-a-saved-edition).
|
||||
For a mistake in an existing edition, fix the source and say in the pull
|
||||
request which editions have the error. A maintainer corrects the saved
|
||||
editions.
|
||||
|
||||
## Release process
|
||||
|
||||
|
||||
@@ -20,7 +20,20 @@ parity gaps when reviewing — but only flag real ones:
|
||||
* Stay silent on internal-only refactors, tests, docs, and changes with no cross-SDK
|
||||
surface.
|
||||
* Parity expectations apply to the Python and TypeScript (`nodejs`) SDKs. Java currently
|
||||
implements only the remote table, not the local/embedded backend, so it is expected to
|
||||
be partial — do not flag Java for missing local-only functionality.
|
||||
implements only Enterprise tables, not the Embedded backend, so it is expected to
|
||||
be partial — do not flag Java for missing Embedded-only functionality.
|
||||
* Keep parity feedback to a short, clearly-labeled note (e.g. "Possible SDK parity
|
||||
gap: …"). It is advisory, not a merge blocker.
|
||||
|
||||
## User-facing text and API compatibility
|
||||
|
||||
Check new user-facing text and public API changes against the rules in `AGENTS.md`:
|
||||
|
||||
* Docs, docstrings, error messages, and examples say "Embedded" and "Enterprise", not
|
||||
"local" or "remote" tables.
|
||||
* Released public APIs are deprecated rather than removed, and released names are not
|
||||
reused for something with a different meaning.
|
||||
* User guides (`docs/web`) document only the current API, with no migration or
|
||||
deprecation notices.
|
||||
* Breaking changes have `!` in the PR title and a `BREAKING CHANGE:` paragraph at the
|
||||
top of the PR body.
|
||||
|
||||
+148
@@ -0,0 +1,148 @@
|
||||
# LanceDB documentation style
|
||||
|
||||
Write for developers who want to understand LanceDB and get something done.
|
||||
Be direct, approachable and technically precise. Give readers enough context
|
||||
to make a decision, then show them how to act on it.
|
||||
|
||||
This guide covers prose on docs.lancedb.com: the pages in this repository's
|
||||
`docs/web`, including the public Enterprise pages, and the Geneva, dataset and
|
||||
REST pages kept in other sources. The
|
||||
[contributing guide](../CONTRIBUTING.md#documentation) covers previewing,
|
||||
code examples and availability labels.
|
||||
|
||||
## Start with the reader's goal
|
||||
|
||||
Open with what the feature does and when to use it. Keep the introduction
|
||||
short. Put prerequisites before the instructions that need them, and explain
|
||||
limitations beside the choice or operation they affect.
|
||||
|
||||
Show the common path before advanced options. A guide should get readers to a
|
||||
useful result before asking them to compare every configuration. This is a
|
||||
default, not a required outline for every page.
|
||||
|
||||
## Give each page a purpose
|
||||
|
||||
A concept page explains a few central ideas and how they relate. A guide helps
|
||||
readers complete a task. A reference describes exact syntax, options and
|
||||
behavior. Link to related material with descriptive link text instead of
|
||||
making every page cover all three roles.
|
||||
|
||||
Keep each section focused on the page's purpose. Don't add a conclusion or a
|
||||
next-steps section unless it helps the reader decide what to do next.
|
||||
|
||||
## Teach through examples
|
||||
|
||||
Use small datasets, meaningful names and examples that build on each other.
|
||||
Include the imports, setup and prerequisites readers need, or clearly link to
|
||||
shared setup. State when successive blocks belong to one program. Show the
|
||||
expected result when it helps readers understand the operation.
|
||||
|
||||
Where equivalent SDK support exists, show Python, TypeScript and Rust
|
||||
consistently. Use the same task and sample data across languages, with
|
||||
idiomatic code in each. If support differs, explain the difference beside the
|
||||
example; don't invent an equivalent API. Prefer fresh example data and make
|
||||
any destructive behavior explicit.
|
||||
|
||||
Explain what an example demonstrates or why an option matters. Avoid narrating
|
||||
every line when the code already makes its meaning clear.
|
||||
|
||||
## Explain choices and consequences
|
||||
|
||||
Tell readers when to choose an option and what changes when they do. State the
|
||||
relevant tradeoff, such as latency versus recall, rather than listing settings
|
||||
without guidance. Use a table when it makes alternatives easier to compare.
|
||||
|
||||
Name the product or component whose behavior you describe. Use LanceDB
|
||||
Enterprise when you mean the offering; use deployment when you mean a
|
||||
particular installation or its configuration. Describe concrete capabilities
|
||||
and benefits without unsupported performance claims or superlatives.
|
||||
|
||||
## Say it directly
|
||||
|
||||
Address the reader as "you" and prefer active verbs and familiar words.
|
||||
Introduce unfamiliar terms when readers first need them. Prefer "use" to
|
||||
"utilize" and "to" to "in order to". Keep technical terms precise: "GPU
|
||||
utilization", for example, has a specific meaning and does not need replacing.
|
||||
|
||||
Describe the subject, not the page or the writing. Instead of "This page is the
|
||||
concept; the SQL reference is the specification", explain the concept and
|
||||
link to the reference. Instead of opening with "That matters", state the
|
||||
consequence. Avoid "simply" and "obviously" when they assume a task is easy for
|
||||
the reader. These are writing guidelines, not blanket bans on individual words.
|
||||
|
||||
## Headings
|
||||
|
||||
A heading names the task or topic of its section. "Then what" doesn't; "Choose
|
||||
an output" does. Prefer specific headings such as "Data durability" to broad
|
||||
questions such as "What survives?". Use sentence case, preserving product names
|
||||
and identifiers.
|
||||
|
||||
## Names
|
||||
|
||||
Write product names exactly: LanceDB, LanceDB Embedded and LanceDB Enterprise.
|
||||
Write other names as their owners do, such as Hugging Face, LangChain,
|
||||
TypeScript and Voyage AI.
|
||||
|
||||
- **LanceDB Embedded** is the in-process execution model: the SDK runs
|
||||
database operations inside the application's process and reads Lance tables
|
||||
directly, from local disk or object storage. Don't write "LanceDB OSS",
|
||||
"LanceDB Local" or "local mode".
|
||||
- **LanceDB Enterprise** is the commercial product. Use this name in product
|
||||
descriptions, SDK documentation and architecture explanations: "a LanceDB
|
||||
SDK connects to LanceDB Enterprise". Describe execution directly: query
|
||||
execution, indexing, caching and maintenance run on the service, outside
|
||||
the application. Write "Embedded and Enterprise" when comparing offerings.
|
||||
Don't introduce "LanceDB Distributed" as another name for the product or
|
||||
its execution model. Lowercase "distributed" still describes how a feature
|
||||
works, such as distributed search, caching or training. Use "Enterprise
|
||||
table" or "Enterprise connection" in prose; keep API identifiers such as
|
||||
`RemoteTable` unchanged.
|
||||
- **LanceDB Cloud** is only the legacy hosted service. Keep it where text is
|
||||
specific to that service, such as `db://` URIs with an `api_key` and
|
||||
`region`; otherwise write LanceDB Enterprise.
|
||||
- **Open source** is a property, not a product: "the open-source LanceDB SDKs",
|
||||
"Lance is open source". Where free versus paid is the point, write "LanceDB
|
||||
Embedded (open source)" and "LanceDB Enterprise". Don't use "OSS" as a
|
||||
product name, as in "OSS vs Enterprise".
|
||||
- Internal component names stay out of public text. Write "query node",
|
||||
"executor" and LanceDB Enterprise instead; the `InternalNames` Vale rule
|
||||
lists the names it catches. Geneva is a product name and stays as is.
|
||||
|
||||
Package, module, class and repository names are code, so put them in code
|
||||
font: `lancedb`, `pyarrow`, `HuggingFaceEmbeddings`.
|
||||
|
||||
## Punctuation
|
||||
|
||||
Don't use em dashes in prose, or a double hyphen or spaced en dash in place of
|
||||
one. Use a comma, a colon, parentheses or two sentences. An en dash in a range,
|
||||
such as 1–3, is fine, and so is a table cell that holds only an em dash to mean
|
||||
"none".
|
||||
|
||||
## Automated checks and review
|
||||
|
||||
[Vale](https://vale.sh) checks a small subset of these conventions: product
|
||||
names, dashes, repeated words, a few vague phrases and headings, and a few
|
||||
plain-language substitutions. Findings are advisory and appear on changed
|
||||
lines; they never fail the check. Installation or configuration failures can
|
||||
still fail it. See the [bundled rules](../.github/vale/README.md) for usage and tests.
|
||||
|
||||
Vale cannot verify technical claims, example correctness, SDK coverage or a
|
||||
page's organization. Review those using implementation evidence, tests and
|
||||
feature-owner input. Confirm availability and release status with the owner;
|
||||
do not infer a release promise from an implementation or a passing test.
|
||||
Reader-visible component titles and captions in MDX attributes are also left
|
||||
to review because Vale does not inspect those attributes.
|
||||
|
||||
Use these guidelines as defaults. Reviewers can make exceptions when they
|
||||
improve clarity or accuracy.
|
||||
|
||||
## Exceptions
|
||||
|
||||
When a sentence must break an automated rule, such as a quoted error message,
|
||||
switch off that rule around it and say why in the pull request:
|
||||
|
||||
```mdx
|
||||
{/* vale LanceDB.Dashes = NO */}
|
||||
The server returns "Table not found — check the name".
|
||||
{/* vale LanceDB.Dashes = YES */}
|
||||
```
|
||||
@@ -37,6 +37,14 @@ embedding_functions`. Prefer keyword arguments for optional parameters.
|
||||
|
||||
::: lancedb.db.DBConnection
|
||||
|
||||
Embedded connections support `location=` on `open_table` to open a table from an
|
||||
explicit dataset URI instead of the derived `<database>/<name>.lance` path:
|
||||
|
||||
```python
|
||||
db = lancedb.connect("./data")
|
||||
table = db.open_table("events", location="./datasets/events.lance")
|
||||
```
|
||||
|
||||
Use `db.server_info()` (or `await db.server_info()` on an asynchronous connection)
|
||||
to include the responding server's release, Git revision, build date and Function
|
||||
runtime information in a bug report. It returns a JSON-compatible dictionary and
|
||||
@@ -907,6 +915,18 @@ with `search().with_row_id(True).to_arrow()` and pass the result to the fetch AP
|
||||
One missing or deleted row ID rejects the entire blob-read batch; the APIs do
|
||||
not return partial results.
|
||||
|
||||
Row positions are not row IDs. To read by position, call
|
||||
`take_offsets(offsets, with_row_id=True)` first and pass the resulting `_rowid`
|
||||
values; `fetch_blobs` remains row-ID based. A query result table that carries
|
||||
snapshot metadata keeps the snapshot that produced it on LanceDB Enterprise, so
|
||||
the fetched bytes or files stay pinned if the table changes. Metadata-free
|
||||
inputs, including legacy query responses and plain row-ID lists, are read from
|
||||
the table handle's current snapshot; keep the source unchanged between selection
|
||||
and fetching. Partial snapshot metadata fails explicitly. For `fetch_blob_files`,
|
||||
a snapshot-bound read also fails explicitly when the serving node cannot echo
|
||||
the immutable identity. The basic remote Blob API floor (server 0.5.0) does not
|
||||
by itself provide that echo capability.
|
||||
|
||||
Local and remote `BlobFile` handles prefetch 512 KiB for sequential reads by
|
||||
default. Pass `buffer_size=0` to `fetch_blob_files`, `open_blob_file`, or
|
||||
`open_blob_files` for sparse reads, or choose another window size in bytes.
|
||||
@@ -940,9 +960,42 @@ PyArrow's `RecordBatch.from_pylist(..., schema=...)` cannot convert raw bytes
|
||||
into the blob extension type; use `blob_array` and `RecordBatch.from_arrays`
|
||||
when constructing batches explicitly.
|
||||
|
||||
For external blob references, construct the descriptor struct described by
|
||||
[blob][lancedb.schema.blob], then wrap it with `pa.ExtensionArray.from_storage`.
|
||||
Inline `data` and external `uri` representations are mutually exclusive.
|
||||
For external blob references, use [blob_uri_array][lancedb.blob_uri_array]. It builds the
|
||||
same extension type from URI strings and optional `(position, size)` byte
|
||||
ranges without requiring pylance. Inline `data` and external `uri` representations
|
||||
are mutually exclusive.
|
||||
|
||||
Register the object prefix with [BasePath][lancedb.BasePath] on
|
||||
`create_table(..., initial_bases=[...])` to store a matched absolute blob URI
|
||||
relative to a base and to scope credentials with `base_<id>.<option>` storage
|
||||
options. A create with data stays a single atomic request; without a matching
|
||||
base, pass `allow_external_blob_outside_bases=True` to keep the absolute URI
|
||||
instead. That opt-in still expects a valid absolute URI and applies to one
|
||||
write; a later `add()` needs its own opt-in. When registering several bases,
|
||||
supply distinct explicit non-zero IDs: the pinned Lance release can collide
|
||||
when automatic and explicit IDs are mixed, leaving a listed but unopenable name
|
||||
after a failed create; retrying with distinct explicit IDs succeeds.
|
||||
|
||||
```python
|
||||
from lancedb import BasePath, blob, blob_uri_array
|
||||
|
||||
schema = pa.schema(
|
||||
[
|
||||
pa.field("id", pa.int64()),
|
||||
blob("video").with_metadata({"lancedb:logical_type": "mp4"}),
|
||||
]
|
||||
)
|
||||
videos = blob_uri_array(
|
||||
["s3://bucket/clip-0.mp4", "s3://bucket/clip-1.mp4"],
|
||||
positions=[0, 0],
|
||||
sizes=[1 << 20, 1 << 20],
|
||||
)
|
||||
db.create_table(
|
||||
"videos",
|
||||
data=pa.RecordBatch.from_arrays([pa.array([0, 1]), videos], schema=schema),
|
||||
initial_bases=[BasePath("s3://bucket")],
|
||||
)
|
||||
```
|
||||
|
||||
LanceDB Enterprise SQL returns blob bytes by default. Select `blob_descriptor(video)` to
|
||||
return an openable reference instead, then use
|
||||
@@ -1004,6 +1057,10 @@ so the fetch APIs cannot read their bytes yet.
|
||||
|
||||
::: lancedb.schema.blob_array
|
||||
|
||||
::: lancedb.blob_uri_array
|
||||
|
||||
::: lancedb.BasePath
|
||||
|
||||
::: lancedb._blob.BlobFile
|
||||
options:
|
||||
show_root_full_path: false
|
||||
|
||||
@@ -35,6 +35,9 @@ rows = tbl.take_row_ids([1001, 1002, 1005]).to_arrow()
|
||||
|
||||
# By offset -- the full range is always [0, len(tbl))
|
||||
rows = tbl.take_offsets([0, 1, 2]).to_arrow()
|
||||
|
||||
# By offset in input order; missing offsets are omitted
|
||||
rows = tbl.take_offsets([2, 0, 2], preserve_order=True).to_arrow()
|
||||
```
|
||||
|
||||
```typescript TypeScript icon="square-js"
|
||||
@@ -53,6 +56,13 @@ let rows_by_id = tbl.take_row_ids(vec![1001, 1002, 1005]).execute().await?;
|
||||
|
||||
// By offset -- the full range is always [0, tbl.count_rows().await?)
|
||||
let rows_by_offset = tbl.take_offsets(vec![0, 1, 2]).execute().await?;
|
||||
|
||||
// By offset in input order; missing offsets are omitted
|
||||
let rows_by_offset_in_order = tbl
|
||||
.take_offsets(vec![2, 0, 2])
|
||||
.preserve_order()
|
||||
.execute()
|
||||
.await?;
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
@@ -74,19 +84,26 @@ sampling with replacement. In Rust, an explicit nonempty
|
||||
`QueryBase::order_by` list overrides the requested order; limits and offsets
|
||||
apply after restoring repeated rows.
|
||||
|
||||
`take_offsets` also preserves repeated offsets, but does not guarantee
|
||||
input order. It tracks `_rowoffset` internally to restore repeated rows
|
||||
and drops that column from the output unless you explicitly `select` it.
|
||||
Add `_rowoffset` to your selection when you need to align a `take_offsets`
|
||||
result with the input offsets.
|
||||
`take_offsets` preserves repeated offsets. By default, it does not guarantee
|
||||
input order and returns found rows as they arrive. Python sync and async
|
||||
builders accept `preserve_order=True`, and Rust accepts `.preserve_order()`,
|
||||
to return found rows in input order, including repeated offsets. Missing
|
||||
non-negative offsets are omitted; negative offsets are rejected and are not
|
||||
Python-style relative indices. The default unordered path remains the
|
||||
existing incremental behavior.
|
||||
|
||||
The method tracks `_rowoffset` internally to restore repeated rows and drops
|
||||
that column from the output unless you explicitly `select` it. Add
|
||||
`_rowoffset` to your selection when you need to align a `take_offsets` result
|
||||
with the input offsets.
|
||||
|
||||
<Note>
|
||||
Ordered takes by row ID collect all matching batches, combine them into one
|
||||
batch and reorder the rows before returning output batches. Even
|
||||
`to_batches(max_batch_length=1)` only limits the returned batch size; it
|
||||
does not bound working memory. For large requests or rows with large
|
||||
column values, split the input IDs into smaller requests and use
|
||||
`.select(...)` to fetch only the columns you need.
|
||||
Ordered takes by row ID, and ordered offset takes with `preserve_order=True`,
|
||||
collect all matching batches, combine them into one batch and reorder the rows
|
||||
before returning output batches. Even `to_batches(max_batch_length=1)` only
|
||||
limits the returned batch size; it does not bound working memory. For large
|
||||
requests or rows with large column values, split the input IDs or offsets into
|
||||
smaller requests and use `.select(...)` to fetch only the columns you need.
|
||||
</Note>
|
||||
|
||||
Offsets are mostly useful for sampling: the valid range is always
|
||||
|
||||
@@ -121,9 +121,11 @@ That is also why a function must declare the environment it needs.
|
||||
|
||||
## Recovering from a failure {#failures}
|
||||
|
||||
A function that raises fails the job. There is no per-row retry or skip policy
|
||||
in the function definition, so a function calling a flaky external service
|
||||
should handle that itself, inside the function body.
|
||||
By default, a refresh skips rows where the function raises and records their
|
||||
errors, up to a 5% failed-row ceiling; see
|
||||
[Handle Function failures](/management/function-failures). A function can also
|
||||
declare a retry policy for transient errors with `@function(retry_policy=...)`
|
||||
where the SDK, server and Function image support it.
|
||||
|
||||
When a refresh fails, fix the cause and run the refresh
|
||||
again. The new refresh fills what is still empty or stale. How much of the
|
||||
|
||||
@@ -536,8 +536,9 @@ refresh value overrides that default for this execution only.
|
||||
|
||||
`batch_size` caps rows in one Function call; LanceDB adapts actual call and
|
||||
work sizes. For Function columns, the refresh defaults to
|
||||
`error_policy = 'fail'`. Set `error_policy = 'skip'` to write null outputs for
|
||||
failing rows and record them in the error store, subject to failure limits.
|
||||
`error_policy = 'skip'` with a 5% failed-row ceiling: failing rows keep any
|
||||
existing output, unassigned outputs stay unassigned, and their errors are
|
||||
recorded in the error store. Set `error_policy = 'fail'` to stop on a row error.
|
||||
See the [SQL refresh options](/sql/dml/refresh-column#options).
|
||||
|
||||
{/*
|
||||
|
||||
@@ -11,18 +11,16 @@ availability:
|
||||
|
||||
A Function refresh can encounter a bad row, fail to initialize a model, lose
|
||||
a worker, or fail while publishing results. These need different remedies.
|
||||
The native workflow below is draft guidance for an unreleased SDK and a
|
||||
matching Enterprise server. The recipes that follow it remain available for
|
||||
older deployments.
|
||||
The native workflow below needs a recent SDK and a matching Enterprise server.
|
||||
The recipes that follow it remain available for older deployments.
|
||||
|
||||
## Draft native workflow: server contract version 1 {#native}
|
||||
## Native workflow: server contract version 1 {#native}
|
||||
|
||||
This section requires the SDK changes in [PR #5048](https://github.com/lancedb/lancedb/pull/5048)
|
||||
and an Enterprise deployment advertising `workflow_version >= 1` in its
|
||||
Function error response. No released SDK or Enterprise version is implied by
|
||||
this draft. The SDK checks this capability before submitting native retry,
|
||||
upgrade, quarantine, history or provenance requests, and rejects unsupported
|
||||
servers before changing the column.
|
||||
This section requires Python SDK 0.42.0b19 or later and an Enterprise
|
||||
deployment advertising `workflow_version >= 1` in its Function error response.
|
||||
The SDK checks this capability before submitting native retry, upgrade,
|
||||
quarantine, history or provenance requests, and rejects unsupported servers
|
||||
before changing the column.
|
||||
|
||||
New Function refreshes default to `error_policy="skip"` with a 5% failed-row
|
||||
ceiling. Successful outputs are published before a threshold failure is
|
||||
@@ -145,8 +143,9 @@ remain unchanged.
|
||||
|
||||
## Choose a row-error policy {#policy}
|
||||
|
||||
The default `fail` stops the job on a row error. `skip` writes null outputs for
|
||||
failed rows and records errors, subject to the refresh's failure limits:
|
||||
On these deployments, the default `fail` stops the job on a row error. `skip`
|
||||
retains a failed row's existing output, leaves an unassigned output unassigned
|
||||
and records errors, subject to the refresh's failure limits:
|
||||
|
||||
```python
|
||||
job = table.refresh_column_async(
|
||||
|
||||
@@ -696,23 +696,25 @@ full worked example.
|
||||
For the full skip, inspect, grouped-error, stable-row-ID retry and quarantine
|
||||
workflow, see [Handle Function failures](/management/function-failures).
|
||||
|
||||
By default, a Function that raises fails the refresh job. Choose how the
|
||||
refresh handles row errors with its error policy:
|
||||
By default, a refresh skips rows where the Function raises, up to a 5%
|
||||
failed-row ceiling. Choose how the refresh handles row errors with its error
|
||||
policy:
|
||||
|
||||
<CodeGroup>
|
||||
```sql SQL icon="database"
|
||||
REFRESH COLUMN embedding ON documents WITH (error_policy = 'skip')
|
||||
REFRESH COLUMN embedding ON documents WITH (error_policy = 'fail')
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
`skip` writes null outputs for failing rows and records their errors. Inspect
|
||||
`skip` retains a failing row's existing output, leaves an unassigned output
|
||||
unassigned and records the error. Inspect
|
||||
them with `SHOW ERRORS` or `table.function_errors()`. Failure limits still
|
||||
apply, and initialization or infrastructure failures can still fail the job.
|
||||
See the [SQL refresh options](/sql/dml/refresh-column#options). A Function
|
||||
that calls a transiently failing external service can handle bounded retries
|
||||
inside its body.
|
||||
|
||||
Letting the job fail is the other option: fix the cause and refresh again. The
|
||||
`fail` is the opt-in alternative: fix the cause and refresh again. The
|
||||
next unfiltered refresh [skips rows that are filled and current](/feature-engineering/refresh-column#idempotent),
|
||||
but how much of the failed job's work was kept is not guaranteed, so do not
|
||||
count on the retry costing only the rows that did not complete. A refresh with
|
||||
|
||||
@@ -59,7 +59,7 @@ to let LanceDB track which outputs need updating.
|
||||
| `batch_size` | maximum rows passed to one Function call; actual calls can be smaller. Function columns only |
|
||||
| `max_executor_processes_per_worker` | cap on executor processes per worker. Function columns only |
|
||||
| `row_timeout_seconds` | deadline for one Function call. Function columns only |
|
||||
| `error_policy` | `'fail'` (default) stops on a row error; `'skip'` writes null outputs and records row errors, subject to failure limits. Function columns only |
|
||||
| `error_policy` | `'skip'` (default, with a 5% failed-row ceiling) retains a failing row's existing output, leaves unassigned outputs unassigned and records row errors, subject to failure limits; `'fail'` stops on a row error. Function columns only |
|
||||
| `max_failed_fraction` | fail the job once more than this share of rows has failed. Function columns only |
|
||||
| `max_failed_rows` | fail the job once more than this many rows has failed. Function columns only |
|
||||
|
||||
|
||||
@@ -50,32 +50,72 @@ LanceDB's `lancedb.util.tbl_to_tensor` helper as PyTorch's `collate_fn`; it conv
|
||||
column-major `torch.Tensor` with shape `(columns, rows)`.
|
||||
|
||||
`Permutation` works differently: its default output is a list of Python dicts, which PyTorch's default collate function
|
||||
can batch into a dict of tensors. This is usually more convenient when you are getting started. However, there is a
|
||||
significant performance penalty converting from Arrow, Lance's internal representation, to this default format. If you
|
||||
want the default PyTorch dict-of-tensors behavior, use a `Permutation` as-is; if you want direct Arrow-to-tensor
|
||||
conversion, either pass `lancedb.util.tbl_to_tensor` as `collate_fn` with a direct `Table` or configure a `Permutation`
|
||||
with one of the transform formats described below.
|
||||
can batch into a dict of tensors. However, converting every value to a Python object has a significant performance
|
||||
penalty. To convert the Arrow data in different ways, call `with_format()` with one of the formats below. Here `B` is
|
||||
the batch size, `C` is the number of columns, and `*S` is the shape of one sample.
|
||||
|
||||
To address this, the `Permutation` class provides a set of builtin transform functions that can be applied to map
|
||||
the Arrow data in different ways. The `arrow` and `polars` formats will always avoid data copies. However, `numpy`,
|
||||
`pandas`, and `torch_col` formats will also avoid data copies in most cases. The `python`, `python_col`, and
|
||||
`torch` formats will all require at least one full copy of the data and are the slowest options.
|
||||
| Format | Output of `iter(batch_size=B)` | DataLoader collate |
|
||||
|---|---|---|
|
||||
| `"arrow"` | `pyarrow.RecordBatch` | Not accepted directly |
|
||||
| `"torch_dict"` | `dict[str, Tensor]`, one `(B, *S)` tensor per column | Identity function |
|
||||
| `"torch"` | `list[dict[str, Tensor]]`, one `(*S)` tensor per column per row | Default collate produces `dict[str, Tensor]` with `(B, *S)` |
|
||||
| `"torch_col"` | One `(C, B, *S)` tensor | Identity function |
|
||||
| `"torch_row"` | `list[Tensor]`, one `(C, *S)` tensor per row | Default collate produces `(B, C, *S)` |
|
||||
| `"numpy"` | One NumPy ndarray | Not accepted directly |
|
||||
|
||||
`torch_dict` is usually the best choice for training because it keeps column names, handles columns with different
|
||||
sample shapes, and shares Arrow storage where the layout allows. `torch_col` and `torch_row` require every column to
|
||||
have the same sample shape. `torch_row` combines numeric dtypes with `torch.promote_types`, and `torch_col` promotes
|
||||
supported mixed numeric dtypes through `torch.stack`. If they see mixed scalar and vector columns, they name the
|
||||
mismatched fields and shapes and point you to `torch_dict`.
|
||||
|
||||
`torch_dict`, `torch`, and `torch_col` reject null values. `torch_row` preserves the previous NaN behavior for
|
||||
nullable scalar integer and floating columns, but rejects nulls in nested fixed-size-list and tensor columns. Use the
|
||||
`"python"` or `"arrow"` format for other nullable columns, or drop/fill the nulls first. `lance.bfloat16` values are
|
||||
supported when the leaf field is `fixed_size_binary[2]` with the `ARROW:extension:name` metadata set to
|
||||
`lance.bfloat16`; these become `torch.bfloat16` tensors. An unmarked binary column is rejected rather than guessed to
|
||||
be bfloat16.
|
||||
|
||||
The `numpy` format returns one ndarray built with `batch.to_pandas().to_numpy()`. The pandas conversion may copy data
|
||||
and may promote mixed numeric columns to a common numeric dtype, for example int64 and float32 to float64. Nested,
|
||||
list, or incompatible columns produce an object ndarray rather than a numeric array.
|
||||
|
||||
### Using torch_dict with a torch data loader {#using-torch-dict-with-a-torch-data-loader}
|
||||
|
||||
`torch_dict` produces a dictionary of per-column tensors for each batch. Pass an identity function as `collate_fn` so
|
||||
PyTorch returns that dictionary unchanged. Scalar columns have shape `(B,)`, a `FixedSizeList<float, D>` column has
|
||||
shape `(B, D)`, and nested fixed-size lists contribute one dimension per level. Fixed-shape tensor columns use their
|
||||
logical shape, with the Arrow axis permutation applied as a view.
|
||||
|
||||
<CodeGroup>
|
||||
```python Python icon="python"
|
||||
import torch
|
||||
from lancedb.permutation import Permutation
|
||||
|
||||
permutation = Permutation.identity(table).with_format("torch_dict")
|
||||
dataloader = torch.utils.data.DataLoader(
|
||||
permutation,
|
||||
batch_size=1024,
|
||||
shuffle=True,
|
||||
collate_fn=lambda batch: batch,
|
||||
)
|
||||
|
||||
for batch in dataloader:
|
||||
print(batch["id"].shape) # (1024,)
|
||||
print(batch["vector"].shape) # (1024, 128)
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
When `num_workers > 0`, replace the lambda with a picklable top-level function that returns its argument.
|
||||
|
||||
### Using the torch column format with a torch data loader {#using-the-torch-column-format-with-a-torch-data-loader}
|
||||
|
||||
The `torch_col` format is the most efficient way to convert from Arrow to a `torch.Tensor`. It will convert the
|
||||
entire Arrow batch to a _column-major_ `torch.Tensor`. In other words, given C columns and R rows, the resulting
|
||||
Tensor will have shape `(C, R)`. However, this format generates an error if you are using a
|
||||
`torch.utils.data.DataLoader` with the default collation function:
|
||||
The `torch_col` format converts the entire Arrow batch to one tensor with shape `(C, B, *S)`. For a table of scalar
|
||||
columns this is the familiar `(columns, rows)` tensor. For a single column it is an `unsqueeze(0)` view of the
|
||||
per-column tensor, so no data is copied; stacking multiple columns does copy.
|
||||
|
||||
```text
|
||||
TypeError: stack(): argument 'tensors' (position 1) must be tuple of Tensors, not Tensor
|
||||
```
|
||||
|
||||
This error occurs because the default collation function does not currently expect a single two-dimensional tensor.
|
||||
It expects a list of tensors which it will then stack. This is what is output by the `torch` format but that format
|
||||
requires a data copy. To avoid this error, and avoid data copies, you will need to provide a custom collation function
|
||||
in addition to specifying the `torch_col` format.
|
||||
PyTorch's default collate does not accept a single multi-dimensional tensor. Pass an identity function as `collate_fn`
|
||||
to receive the tensor directly from the data loader.
|
||||
|
||||
<CodeGroup>
|
||||
```python Python icon="python"
|
||||
@@ -86,8 +126,6 @@ dataloader = torch.utils.data.DataLoader(permutation, collate_fn=lambda x: x)
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
This will now output a single two-dimensional tensor for each batch.
|
||||
|
||||
## 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
|
||||
|
||||
@@ -38,7 +38,7 @@ from .db import AsyncConnection, DBConnection, LanceDBConnection
|
||||
from .remote import ClientConfig
|
||||
from .remote.db import RemoteDBConnection
|
||||
from .expr import Expr, col, lit, func
|
||||
from .schema import blob, vector
|
||||
from .schema import BasePath, blob, blob_uri_array, vector
|
||||
from ._blob_reader import BlobReader as BlobReader
|
||||
from .job import AsyncJob, Job
|
||||
from .sql import AsyncQuery as AsyncSqlQuery
|
||||
@@ -696,6 +696,8 @@ __all__ = [
|
||||
"sanitize_uri",
|
||||
"blob",
|
||||
"BlobType",
|
||||
"BasePath",
|
||||
"blob_uri_array",
|
||||
"vector",
|
||||
"DBConnection",
|
||||
"Job",
|
||||
|
||||
@@ -7,7 +7,9 @@ from __future__ import annotations
|
||||
|
||||
import io
|
||||
import operator
|
||||
import re
|
||||
from collections.abc import Awaitable, Callable, Iterable, Mapping
|
||||
from dataclasses import dataclass
|
||||
from typing import TYPE_CHECKING, Optional, Union
|
||||
|
||||
import pyarrow as pa
|
||||
@@ -30,10 +32,47 @@ BLOB_MODE_TO_HANDLING = {
|
||||
}
|
||||
|
||||
ROW_ID_FIELD_NAME = "_lance_row_id"
|
||||
QUERY_VERSION_METADATA_KEY = b"lancedb:query_version"
|
||||
QUERY_SNAPSHOT_METADATA_KEY = b"lancedb:query_snapshot"
|
||||
|
||||
FetchBlobsSync = Callable[[str, list[int]], pa.Array | pa.ChunkedArray]
|
||||
FetchBlobsAsync = Callable[[str, list[int]], Awaitable[pa.Array | pa.ChunkedArray]]
|
||||
|
||||
_POSITION_HELP = (
|
||||
"If you only have row positions, call "
|
||||
"table.take_offsets(offsets, with_row_id=True) first and pass the resulting "
|
||||
"'_rowid' values."
|
||||
)
|
||||
|
||||
|
||||
def _remote_blob_snapshot(
|
||||
schema: pa.Schema, *, operation: str = "blob_mode='bytes'"
|
||||
) -> tuple[int, str]:
|
||||
"""Validate the snapshot metadata a remote query attaches to its result."""
|
||||
value = (schema.metadata or {}).get(QUERY_VERSION_METADATA_KEY, b"")
|
||||
if not value.isdigit() or not 0 < int(value) < 2**64:
|
||||
raise NotImplementedError(
|
||||
f"{operation} requires a stable table snapshot: the query response "
|
||||
"has a missing, invalid, or inconsistent x-lancedb-query-version header. "
|
||||
"Upgrade the server and use a table without Realtime/MemWAL, or use "
|
||||
"blob_mode='descriptions'."
|
||||
)
|
||||
identity = (schema.metadata or {}).get(QUERY_SNAPSHOT_METADATA_KEY, b"")
|
||||
if not re.fullmatch(rb"v1:[0-9a-f]{64}", identity):
|
||||
raise NotImplementedError(
|
||||
f"{operation} requires a trustworthy query snapshot identity: "
|
||||
"missing or unsupported x-lancedb-query-snapshot. Upgrade the server "
|
||||
"on every serving node, or use blob_mode='descriptions'."
|
||||
)
|
||||
return int(value), identity.decode("ascii")
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class _BlobRowIdSelection:
|
||||
row_ids: list[int]
|
||||
version: Optional[int] = None
|
||||
snapshot_identity: Optional[str] = None
|
||||
|
||||
|
||||
def _validate_blob_buffer_size(size: Optional[int]) -> Optional[int]:
|
||||
if size is None:
|
||||
@@ -376,7 +415,7 @@ def _hit_row_ids(tbl: pa.Table, blob_sources: dict[str, str]) -> list[int]:
|
||||
raise ValueError(
|
||||
f"query result has no '_rowid' column and no '{ROW_ID_FIELD_NAME}' "
|
||||
f"field on blob columns {list(blob_sources)}. Call .with_row_id(True) "
|
||||
"to fetch blob bytes for this query."
|
||||
f"to fetch blob bytes for this query. {_POSITION_HELP}"
|
||||
)
|
||||
|
||||
|
||||
@@ -417,7 +456,8 @@ def read_row_ids_from_hits(hits: pa.Table, blob_column: str) -> list[int]:
|
||||
raise ValueError(
|
||||
f"query result has no '_rowid' column and no '{ROW_ID_FIELD_NAME}' "
|
||||
f"field on blob column '{blob_column}'. Pass fresh blob query "
|
||||
"results, call .with_row_id(True), or pass a list of row ids."
|
||||
f"results, call .with_row_id(True), or pass a list of row ids. "
|
||||
f"{_POSITION_HELP}"
|
||||
)
|
||||
|
||||
|
||||
@@ -638,11 +678,31 @@ def _walk_struct_fields(
|
||||
return data_type
|
||||
|
||||
|
||||
def _query_snapshot_for_blob_fetch(
|
||||
schema: pa.Schema,
|
||||
) -> Optional[tuple[int, str]]:
|
||||
"""Use the query snapshot when a result table carries one.
|
||||
|
||||
A table without either metadata key came from a local table or a server
|
||||
that cannot pin deferred reads, so row ids keep their existing
|
||||
current-snapshot behavior.
|
||||
"""
|
||||
metadata = schema.metadata or {}
|
||||
if not any(
|
||||
key in metadata
|
||||
for key in (QUERY_VERSION_METADATA_KEY, QUERY_SNAPSHOT_METADATA_KEY)
|
||||
):
|
||||
return None
|
||||
return _remote_blob_snapshot(schema, operation="fetching blobs for a query result")
|
||||
|
||||
|
||||
def _normalize_blob_row_ids(
|
||||
row_ids: Union[list[int], pa.Array, pa.ChunkedArray, pa.Table], blob_column: str
|
||||
) -> list[int]:
|
||||
) -> _BlobRowIdSelection:
|
||||
snapshot = None
|
||||
if isinstance(row_ids, pa.Table):
|
||||
values = read_row_ids_from_hits(row_ids, blob_column)
|
||||
snapshot = _query_snapshot_for_blob_fetch(row_ids.schema)
|
||||
elif isinstance(row_ids, (pa.Array, pa.ChunkedArray)):
|
||||
if not pa.types.is_integer(row_ids.type):
|
||||
raise ValueError(
|
||||
@@ -662,7 +722,8 @@ def _normalize_blob_row_ids(
|
||||
if row_id < 0:
|
||||
raise ValueError("row ids must be non-negative")
|
||||
normalized.append(row_id)
|
||||
return normalized
|
||||
version, snapshot_identity = snapshot if snapshot else (None, None)
|
||||
return _BlobRowIdSelection(normalized, version, snapshot_identity)
|
||||
|
||||
|
||||
def _wrap_blob_files(handles: Iterable[object]) -> list[Optional[BlobFile]]:
|
||||
|
||||
@@ -334,6 +334,9 @@ class Connection(object):
|
||||
namespace_path: Optional[List[str]] = None,
|
||||
storage_options: Optional[Dict[str, str]] = None,
|
||||
location: Optional[str] = None,
|
||||
namespace_client: Optional[Any] = None,
|
||||
initial_bases: Optional[List[Any]] = None,
|
||||
allow_external_blob_outside_bases: bool = False,
|
||||
) -> Table: ...
|
||||
async def create_empty_table(
|
||||
self,
|
||||
@@ -343,6 +346,8 @@ class Connection(object):
|
||||
namespace_path: Optional[List[str]] = None,
|
||||
storage_options: Optional[Dict[str, str]] = None,
|
||||
location: Optional[str] = None,
|
||||
namespace_client: Optional[Any] = None,
|
||||
initial_bases: Optional[List[Any]] = None,
|
||||
) -> Table: ...
|
||||
async def open_table(
|
||||
self,
|
||||
@@ -570,6 +575,7 @@ class Table:
|
||||
def _is_native(self) -> bool: ...
|
||||
def close(self) -> None: ...
|
||||
async def schema(self) -> pa.Schema: ...
|
||||
def schema_sync(self) -> pa.Schema: ...
|
||||
async def add(
|
||||
self,
|
||||
data: pa.RecordBatchReader,
|
||||
@@ -857,7 +863,13 @@ class Table:
|
||||
requests: Sequence[Sequence[int]],
|
||||
) -> pa.LargeBinaryArray: ...
|
||||
async def fetch_blob_files(
|
||||
self, column: str, row_ids: list[int], buffer_size: Optional[int] = None
|
||||
self,
|
||||
column: str,
|
||||
row_ids: list[int],
|
||||
buffer_size: Optional[int] = None,
|
||||
*,
|
||||
version: Optional[int] = None,
|
||||
snapshot_identity: Optional[str] = None,
|
||||
) -> list[Optional[BlobFile]]: ...
|
||||
async def open_blob_file(
|
||||
self, descriptor: str, buffer_size: Optional[int] = None
|
||||
@@ -965,6 +977,9 @@ class Query:
|
||||
async def execute_to_reader(
|
||||
self, max_batch_length: Optional[int], timeout: Optional[timedelta]
|
||||
) -> pa.RecordBatchReader: ...
|
||||
def execute_to_reader_sync(
|
||||
self, max_batch_length: Optional[int], timeout: Optional[timedelta]
|
||||
) -> pa.RecordBatchReader: ...
|
||||
async def explain_plan(self, verbose: Optional[bool]) -> str: ...
|
||||
async def analyze_plan(
|
||||
self, distributed_metrics: Optional[AnalyzePlanDistributedMetrics] = None
|
||||
@@ -974,6 +989,7 @@ class Query:
|
||||
class TakeQuery:
|
||||
def select(self, columns: List[str]): ...
|
||||
def with_row_id(self): ...
|
||||
def preserve_order(self): ...
|
||||
def use_rte(self, enable: bool): ...
|
||||
async def output_schema(self) -> pa.Schema: ...
|
||||
async def execute(self) -> RecordBatchStream: ...
|
||||
@@ -1009,6 +1025,9 @@ class FTSQuery:
|
||||
async def execute_to_reader(
|
||||
self, max_batch_length: Optional[int], timeout: Optional[timedelta]
|
||||
) -> pa.RecordBatchReader: ...
|
||||
def execute_to_reader_sync(
|
||||
self, max_batch_length: Optional[int], timeout: Optional[timedelta]
|
||||
) -> pa.RecordBatchReader: ...
|
||||
async def explain_plan(self, verbose: Optional[bool]) -> str: ...
|
||||
async def analyze_plan(
|
||||
self, distributed_metrics: Optional[AnalyzePlanDistributedMetrics] = None
|
||||
@@ -1021,6 +1040,9 @@ class VectorQuery:
|
||||
async def execute_to_reader(
|
||||
self, max_batch_length: Optional[int], timeout: Optional[timedelta]
|
||||
) -> pa.RecordBatchReader: ...
|
||||
def execute_to_reader_sync(
|
||||
self, max_batch_length: Optional[int], timeout: Optional[timedelta]
|
||||
) -> pa.RecordBatchReader: ...
|
||||
def where(self, filter: str): ...
|
||||
def where_expr(self, expr: PyExpr): ...
|
||||
def select(self, columns: List[Tuple[str, str]]): ...
|
||||
@@ -1081,6 +1103,7 @@ class PyQueryRequest:
|
||||
offset: Optional[int]
|
||||
take_offsets: Optional[List[int]]
|
||||
take_row_ids: Optional[List[int]]
|
||||
preserve_order: Optional[bool]
|
||||
filter: Optional[Union[str, bytes]]
|
||||
full_text_search: Optional[FullTextQuery]
|
||||
select: Optional[Union[str, List[str]]]
|
||||
|
||||
@@ -507,6 +507,8 @@ class DBConnection(EnforceOverrides):
|
||||
storage_options: Optional[Dict[str, str]] = None,
|
||||
data_storage_version: Optional[str] = None,
|
||||
enable_v2_manifest_paths: Optional[bool] = None,
|
||||
initial_bases: Optional[List[Any]] = None,
|
||||
allow_external_blob_outside_bases: bool = False,
|
||||
) -> Table:
|
||||
"""Create a [Table][lancedb.table.Table] in the database.
|
||||
|
||||
@@ -570,6 +572,23 @@ class DBConnection(EnforceOverrides):
|
||||
enable_v2_manifest_paths: optional, bool, default False
|
||||
Deprecated. Set `storage_options` when connecting to the database and set
|
||||
`new_table_enable_v2_manifest_paths` in the options.
|
||||
initial_bases: list, optional
|
||||
Storage bases to register in the table's manifest in the same
|
||||
commit that creates it, so a create with data stays atomic. Each
|
||||
entry can be a [BasePath][lancedb.schema.BasePath], a dict with
|
||||
`path`, `name`, `is_dataset_root`, and `id` keys, or a
|
||||
`lance.DatasetBasePath`. Blob URIs that fall under a registered
|
||||
base are stored relative to it; other URIs need
|
||||
`allow_external_blob_outside_bases=True`. `None` and an empty
|
||||
list are equivalent. When supplying IDs for multiple bases, use
|
||||
distinct explicit non-zero IDs; [BasePath][lancedb.schema.BasePath]
|
||||
describes the pinned-Lance limitation.
|
||||
allow_external_blob_outside_bases: bool, default False
|
||||
Store blob URIs that do not fall under a registered base. The row
|
||||
keeps a reference, so the objects have to stay readable. Set
|
||||
`initial_bases` instead when the URIs share a registered prefix.
|
||||
Defaults to rejecting such URIs. The opt-in applies only to the
|
||||
initial data; a later `add()` must enable it again.
|
||||
Returns
|
||||
-------
|
||||
LanceTable
|
||||
@@ -2156,6 +2175,8 @@ class LanceDBConnection(DBConnection):
|
||||
storage_options: Optional[Dict[str, str]] = None,
|
||||
data_storage_version: Optional[str] = None,
|
||||
enable_v2_manifest_paths: Optional[bool] = None,
|
||||
initial_bases: Optional[List[Any]] = None,
|
||||
allow_external_blob_outside_bases: bool = False,
|
||||
) -> LanceTable:
|
||||
"""Create a table in the database.
|
||||
|
||||
@@ -2186,6 +2207,8 @@ class LanceDBConnection(DBConnection):
|
||||
storage_options=storage_options,
|
||||
data_storage_version=data_storage_version,
|
||||
enable_v2_manifest_paths=enable_v2_manifest_paths,
|
||||
initial_bases=initial_bases,
|
||||
allow_external_blob_outside_bases=allow_external_blob_outside_bases,
|
||||
)
|
||||
return tbl
|
||||
|
||||
@@ -2197,6 +2220,7 @@ class LanceDBConnection(DBConnection):
|
||||
namespace_path: Optional[List[str]] = None,
|
||||
storage_options: Optional[Dict[str, str]] = None,
|
||||
index_cache_size: Optional[int] = None,
|
||||
location: Optional[str] = None,
|
||||
branch: Optional[str] = None,
|
||||
version: Optional[int] = None,
|
||||
) -> LanceTable:
|
||||
@@ -2209,6 +2233,10 @@ class LanceDBConnection(DBConnection):
|
||||
namespace_path: List[str], optional
|
||||
The namespace to open the table from. When non-empty, the
|
||||
table is resolved through the directory namespace client.
|
||||
location: str, optional
|
||||
The explicit location (URI) of the table. If provided, the table will be
|
||||
opened from this location instead of deriving it from the database URI
|
||||
and table name.
|
||||
branch: str, optional
|
||||
If provided, open a handle scoped to this branch instead of the
|
||||
default branch. Reads and writes operate in the branch's context.
|
||||
@@ -2242,6 +2270,7 @@ class LanceDBConnection(DBConnection):
|
||||
namespace_path=namespace_path,
|
||||
storage_options=storage_options,
|
||||
index_cache_size=index_cache_size,
|
||||
location=location,
|
||||
)
|
||||
except (RuntimeError, ValueError) as e:
|
||||
if namespace_path and (
|
||||
@@ -3290,6 +3319,8 @@ class AsyncConnection(object):
|
||||
embedding_functions: Optional[List[EmbeddingFunctionConfig]] = None,
|
||||
location: Optional[str] = None,
|
||||
namespace_client: Optional[Any] = None,
|
||||
initial_bases: Optional[List[Any]] = None,
|
||||
allow_external_blob_outside_bases: bool = False,
|
||||
) -> AsyncTable:
|
||||
"""Create an [AsyncTable][lancedb.table.AsyncTable] in the database.
|
||||
|
||||
@@ -3347,6 +3378,23 @@ class AsyncConnection(object):
|
||||
To enable stable row IDs (row IDs remain stable after compaction,
|
||||
update, delete, and merges), set `new_table_enable_stable_row_ids`
|
||||
to `"true"` in storage_options when connecting to the database.
|
||||
initial_bases: list, optional
|
||||
Storage bases to register in the table's manifest in the same
|
||||
commit that creates it, so a create with data stays atomic. Each
|
||||
entry can be a [BasePath][lancedb.schema.BasePath], a dict with
|
||||
`path`, `name`, `is_dataset_root`, and `id` keys, or a
|
||||
`lance.DatasetBasePath`. Blob URIs that fall under a registered
|
||||
base are stored relative to it; other URIs need
|
||||
`allow_external_blob_outside_bases=True`. `None` and an empty
|
||||
list are equivalent. When supplying IDs for multiple bases, use
|
||||
distinct explicit non-zero IDs; [BasePath][lancedb.schema.BasePath]
|
||||
describes the pinned-Lance limitation.
|
||||
allow_external_blob_outside_bases: bool, default False
|
||||
Store blob URIs that do not fall under a registered base. The row
|
||||
keeps a reference, so the objects have to stay readable. Requires
|
||||
initial `data`; the opt-in applies only to that initial write, and
|
||||
a later `add()` must enable it again. Defaults to rejecting such
|
||||
URIs.
|
||||
|
||||
Returns
|
||||
-------
|
||||
@@ -3458,6 +3506,25 @@ class AsyncConnection(object):
|
||||
"""
|
||||
if namespace_path is None:
|
||||
namespace_path = []
|
||||
if get_uri_scheme(self.uri) == "db":
|
||||
# The Enterprise create endpoint has no way to express either
|
||||
# option. Reject before sanitizing or reading `data`, and do not
|
||||
# point at a local-only or remote `add` path.
|
||||
if initial_bases:
|
||||
raise NotImplementedError(
|
||||
"initial_bases is not supported for table creation in "
|
||||
"LanceDB Enterprise"
|
||||
)
|
||||
if allow_external_blob_outside_bases:
|
||||
raise NotImplementedError(
|
||||
"allow_external_blob_outside_bases is not supported for table "
|
||||
"creation in LanceDB Enterprise"
|
||||
)
|
||||
if data is None and allow_external_blob_outside_bases:
|
||||
raise ValueError(
|
||||
"allow_external_blob_outside_bases requires initial data; "
|
||||
"pass it to add() for later writes"
|
||||
)
|
||||
metadata = None
|
||||
|
||||
if embedding_functions is not None:
|
||||
@@ -3504,6 +3571,7 @@ class AsyncConnection(object):
|
||||
storage_options=storage_options,
|
||||
location=location,
|
||||
namespace_client=namespace_client,
|
||||
initial_bases=initial_bases,
|
||||
)
|
||||
else:
|
||||
data = data_to_reader(data, schema)
|
||||
@@ -3515,6 +3583,8 @@ class AsyncConnection(object):
|
||||
storage_options=storage_options,
|
||||
location=location,
|
||||
namespace_client=namespace_client,
|
||||
initial_bases=initial_bases,
|
||||
allow_external_blob_outside_bases=allow_external_blob_outside_bases,
|
||||
)
|
||||
|
||||
return AsyncTable(new_table)
|
||||
|
||||
@@ -642,6 +642,8 @@ class LanceNamespaceDBConnection(DBConnection):
|
||||
storage_options: Optional[Dict[str, str]] = None,
|
||||
data_storage_version: Optional[str] = None,
|
||||
enable_v2_manifest_paths: Optional[bool] = None,
|
||||
initial_bases: Optional[List[Any]] = None,
|
||||
allow_external_blob_outside_bases: bool = False,
|
||||
) -> Table:
|
||||
if namespace_path is None:
|
||||
namespace_path = []
|
||||
@@ -663,6 +665,8 @@ class LanceNamespaceDBConnection(DBConnection):
|
||||
embedding_functions=embedding_functions,
|
||||
namespace_path=namespace_path,
|
||||
storage_options=storage_options,
|
||||
initial_bases=initial_bases,
|
||||
allow_external_blob_outside_bases=allow_external_blob_outside_bases,
|
||||
)
|
||||
)
|
||||
|
||||
@@ -1309,6 +1313,8 @@ class AsyncLanceNamespaceDBConnection:
|
||||
storage_options: Optional[Dict[str, str]] = None,
|
||||
data_storage_version: Optional[str] = None,
|
||||
enable_v2_manifest_paths: Optional[bool] = None,
|
||||
initial_bases: Optional[List[Any]] = None,
|
||||
allow_external_blob_outside_bases: bool = False,
|
||||
) -> AsyncTable:
|
||||
"""Create a new table in the namespace."""
|
||||
if namespace_path is None:
|
||||
@@ -1330,6 +1336,8 @@ class AsyncLanceNamespaceDBConnection:
|
||||
namespace_path=namespace_path,
|
||||
embedding_functions=embedding_functions,
|
||||
storage_options=storage_options,
|
||||
initial_bases=initial_bases,
|
||||
allow_external_blob_outside_bases=allow_external_blob_outside_bases,
|
||||
)
|
||||
return table._set_namespace_context(
|
||||
namespace_path=namespace_path,
|
||||
|
||||
@@ -11,7 +11,12 @@ import pyarrow as pa
|
||||
from ._lancedb import async_permutation_builder, PermutationReader
|
||||
from .table import LanceTable, Table
|
||||
from .background_loop import LOOP
|
||||
from .util import batch_to_tensor, batch_to_tensor_dict, batch_to_tensor_rows
|
||||
from .util import (
|
||||
batch_to_tensor,
|
||||
batch_to_tensor_columns,
|
||||
batch_to_tensor_dict,
|
||||
batch_to_tensor_rows,
|
||||
)
|
||||
from typing import Any, Callable, Iterator, Literal, Optional, TYPE_CHECKING, Union
|
||||
|
||||
if TYPE_CHECKING:
|
||||
@@ -1031,6 +1036,7 @@ class Permutation:
|
||||
"pandas",
|
||||
"arrow",
|
||||
"torch",
|
||||
"torch_dict",
|
||||
"torch_row",
|
||||
"torch_col",
|
||||
"polars",
|
||||
@@ -1042,28 +1048,54 @@ class Permutation:
|
||||
If this method is not called, the "python" format will be used.
|
||||
|
||||
The format can be one of:
|
||||
- "numpy" - the batch will be a dict of numpy arrays (one per column)
|
||||
- "numpy" - a single NumPy ndarray built with
|
||||
``batch.to_pandas().to_numpy()``. This conversion may copy data and
|
||||
may promote mixed numeric columns to a common numeric dtype, for
|
||||
example int64 and float32 to float64. Nested or incompatible columns
|
||||
produce an object array.
|
||||
- "python" - the batch will be a list of dicts (one per row)
|
||||
- "python_col" - the batch will be a dict of lists (one entry per column)
|
||||
- "pandas" - the batch will be a pandas DataFrame
|
||||
- "arrow" - the batch will be a pyarrow RecordBatch
|
||||
- "torch" - the batch will be a list of per-row dicts mapping column
|
||||
name to a 0-D torch tensor. Works with the default
|
||||
``torch.utils.data.DataLoader`` collate, which stacks the per-row
|
||||
dicts back into a dict of batched tensors.
|
||||
- "torch_row" - the batch will be a list of tensors, one per row
|
||||
- "torch_col" - the batch will be a 2D torch tensor (first dim indexes columns)
|
||||
- "torch" - a list of per-row dicts mapping column names to tensors with
|
||||
shape ``(*S)``. The default DataLoader collate stacks these into a
|
||||
dict of ``(B, *S)`` tensors.
|
||||
- "torch_dict" - a dict mapping each column name to one tensor with
|
||||
shape ``(B, *S)``. Columns may have different sample shapes ``S``.
|
||||
Use an identity collate to consume the batch directly. Tensors share
|
||||
Arrow storage where the layout allows.
|
||||
- "torch_row" - a list of per-row tensors with shape ``(C, *S)``. All
|
||||
columns must have the same sample shape ``S``. A single scalar column
|
||||
produces ``(1,)`` tensors. Numeric dtypes are combined with
|
||||
``torch.promote_types``.
|
||||
- "torch_col" - one tensor with shape ``(C, B, *S)``. All columns must
|
||||
have the same sample shape ``S``. For one column this is an
|
||||
``unsqueeze(0)`` view of the column tensor.
|
||||
- "polars" - the batch will be a polars DataFrame
|
||||
|
||||
Conversion may or may not involve a data copy. Lance uses Arrow internally
|
||||
and so it is able to zero-copy to the arrow and polars formats.
|
||||
For torch formats, ``S`` is the shape of one sample. Scalar columns have
|
||||
``S = ()``. A fixed-size-list column of width ``D`` contributes a
|
||||
dimension ``D``, and nested fixed-size lists contribute one dimension
|
||||
per level. Fixed-shape tensors use their logical shape, including any
|
||||
axis permutation. "torch_dict", "torch", and "torch_col" reject nulls;
|
||||
use the "python" or "arrow" format for nullable columns. "torch_row"
|
||||
preserves the previous NaN behavior for nullable scalar integer and
|
||||
floating columns, but rejects nulls in nested fixed-size-list and tensor
|
||||
columns.
|
||||
|
||||
Conversion to torch and torch_col will be zero-copy but will only support a
|
||||
subset of data types (numeric types).
|
||||
``lance.bfloat16`` values become ``torch.bfloat16`` tensors when the
|
||||
leaf field is ``fixed_size_binary[2]`` and carries the
|
||||
``ARROW:extension:name`` metadata value ``lance.bfloat16``. Unmarked
|
||||
binary columns are rejected.
|
||||
|
||||
Conversion to numpy and/or pandas will typically be zero-copy for numeric
|
||||
types. Conversion of strings, lists, and structs will require creating python
|
||||
objects and this is not zero-copy.
|
||||
Conversion may or may not involve a data copy. Lance uses Arrow
|
||||
internally and can zero-copy to the arrow and polars formats.
|
||||
"torch_dict", "torch", and a single-column "torch_col" produce
|
||||
numeric and fixed-size-list tensors without copying where the Arrow
|
||||
layout allows. Multi-column "torch_col" and "torch_row" stack columns
|
||||
and therefore copy. Conversion to numpy and/or pandas can copy even
|
||||
homogeneous numeric columns. Conversion of strings, lists, and structs
|
||||
will require creating Python objects and this is not zero-copy.
|
||||
|
||||
For custom formatting, use
|
||||
[with_transform][lancedb.permutation.Permutation.with_transform] which
|
||||
@@ -1082,6 +1114,8 @@ class Permutation:
|
||||
return self.with_transform(Transforms.arrow2arrow)
|
||||
elif format == "torch":
|
||||
return self.with_transform(batch_to_tensor_dict)
|
||||
elif format == "torch_dict":
|
||||
return self.with_transform(batch_to_tensor_columns)
|
||||
elif format == "torch_row":
|
||||
return self.with_transform(batch_to_tensor_rows)
|
||||
elif format == "torch_col":
|
||||
|
||||
+257
-77
@@ -4,7 +4,6 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import re
|
||||
from abc import ABC, abstractmethod
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from datetime import timedelta
|
||||
@@ -48,6 +47,7 @@ from ._blob import (
|
||||
BLOB_MODE_TO_HANDLING,
|
||||
FetchBlobsAsync,
|
||||
FetchBlobsSync,
|
||||
_remote_blob_snapshot,
|
||||
blob_auto_row_id_for_scan,
|
||||
blob_projection_sources,
|
||||
blob_v2_projection_sources,
|
||||
@@ -205,25 +205,6 @@ def _supports_blob_fetch(
|
||||
)
|
||||
|
||||
|
||||
def _remote_blob_snapshot(schema: pa.Schema) -> tuple[int, str]:
|
||||
value = (schema.metadata or {}).get(b"lancedb:query_version", b"")
|
||||
if not value.isdigit() or not 0 < int(value) < 2**64:
|
||||
raise NotImplementedError(
|
||||
"blob_mode='bytes' requires a stable table snapshot: the query response "
|
||||
"has a missing, invalid, or inconsistent x-lancedb-query-version header. "
|
||||
"Upgrade the server and use a table without Realtime/MemWAL, or use "
|
||||
"blob_mode='descriptions'."
|
||||
)
|
||||
identity = (schema.metadata or {}).get(b"lancedb:query_snapshot", b"")
|
||||
if not re.fullmatch(rb"v1:[0-9a-f]{64}", identity):
|
||||
raise NotImplementedError(
|
||||
"blob_mode='bytes' requires a trustworthy query snapshot identity: "
|
||||
"missing or unsupported x-lancedb-query-snapshot. Upgrade the server "
|
||||
"on every serving node, or use blob_mode='descriptions'."
|
||||
)
|
||||
return int(value), identity.decode("ascii")
|
||||
|
||||
|
||||
def _merge_query_snapshot(result: pa.Table, *sources: pa.Table) -> pa.Table:
|
||||
"""Preserve a snapshot only when every query leg used the same identity."""
|
||||
keys = (b"lancedb:query_version", b"lancedb:query_snapshot")
|
||||
@@ -1124,6 +1105,9 @@ class Query(pydantic.BaseModel):
|
||||
The default is False
|
||||
"""
|
||||
|
||||
# Internal: the sync query layer already prepared blob row ids.
|
||||
_blob_row_id_prepared: bool = pydantic.PrivateAttr(default=False)
|
||||
|
||||
# The name of the vector column to use for vector search.
|
||||
vector_column: Optional[str] = None
|
||||
|
||||
@@ -1202,6 +1186,9 @@ class Query(pydantic.BaseModel):
|
||||
# Row IDs whose requested order and duplicate occurrences must be restored.
|
||||
take_row_ids: Optional[List[int]] = None
|
||||
|
||||
# Restore take-offset duplicates in the exact input order.
|
||||
preserve_order: Optional[bool] = None
|
||||
|
||||
# if true, will only search the indexed data
|
||||
fast_search: Optional[bool] = None
|
||||
|
||||
@@ -1228,6 +1215,7 @@ class Query(pydantic.BaseModel):
|
||||
query.offset = req.offset
|
||||
query.take_offsets = req.take_offsets
|
||||
query.take_row_ids = req.take_row_ids
|
||||
query.preserve_order = req.preserve_order
|
||||
query.filter = req.filter
|
||||
query.full_text_query = req.full_text_search
|
||||
query.columns = req.select
|
||||
@@ -1789,23 +1777,85 @@ class LanceQueryBuilder(ABC):
|
||||
def _user_requested_row_id(self) -> bool:
|
||||
return self._with_row_id is True
|
||||
|
||||
def _blob_auto_row_id_enabled(self) -> bool:
|
||||
def _blob_auto_row_id_enabled(self, schema: Optional[pa.Schema] = None) -> bool:
|
||||
if self._with_row_id is not None:
|
||||
return False
|
||||
if schema is None:
|
||||
schema = self._table.schema
|
||||
return blob_auto_row_id_for_scan(
|
||||
self._table.schema,
|
||||
schema,
|
||||
self._columns,
|
||||
with_row_id=self._with_row_id,
|
||||
)
|
||||
|
||||
def _scan_needs_row_id(self) -> bool:
|
||||
return self._user_requested_row_id() or self._blob_auto_row_id_enabled()
|
||||
def _row_id_schema(self) -> Optional[pa.Schema]:
|
||||
if self._with_row_id is not None:
|
||||
return None
|
||||
return self._table.schema
|
||||
|
||||
def _query_for_scan(self, blob_sources: Optional[dict[str, str]] = None) -> Query:
|
||||
def _scan_needs_row_id(self, schema: Optional[pa.Schema] = None) -> bool:
|
||||
if self._user_requested_row_id():
|
||||
return True
|
||||
return self._blob_auto_row_id_enabled(schema)
|
||||
|
||||
def _query_for_scan(
|
||||
self,
|
||||
blob_sources: Optional[dict[str, str]] = None,
|
||||
schema: Optional[pa.Schema] = None,
|
||||
) -> Query:
|
||||
self._ensure_fragment_constraints_supported("this query")
|
||||
query = self.to_query_object()
|
||||
if self._scan_needs_row_id() or blob_sources:
|
||||
if schema is None:
|
||||
schema = self._row_id_schema()
|
||||
if self._scan_needs_row_id(schema) or blob_sources:
|
||||
query.with_row_id = True
|
||||
return query
|
||||
|
||||
def _prepare_blob_execution(
|
||||
self, blob_mode: BlobMode
|
||||
) -> tuple[dict[str, str], Optional[pa.Schema]]:
|
||||
validate_blob_mode(blob_mode)
|
||||
schema = self._table.schema
|
||||
if blob_mode == "lazy":
|
||||
if not schema_has_blob_field(schema):
|
||||
return {}, schema
|
||||
# Lazy results hide automatic row ids inside projected blob columns.
|
||||
return blob_v2_projection_sources(schema, self._columns), schema
|
||||
return self._validated_blob_sources(blob_mode, schema), schema
|
||||
|
||||
def _to_batches_prepared(
|
||||
self,
|
||||
*,
|
||||
batch_size: Optional[int],
|
||||
timeout: Optional[timedelta],
|
||||
blob_mode: BlobMode,
|
||||
blob_sources: dict[str, str],
|
||||
schema: Optional[pa.Schema],
|
||||
) -> pa.RecordBatchReader:
|
||||
query = self._query_for_scan(blob_sources, schema)
|
||||
reader = self._execute_query_prepared(
|
||||
query, batch_size=batch_size, timeout=timeout
|
||||
)
|
||||
return self._batches_in_mode(reader, blob_mode, blob_sources, schema)
|
||||
|
||||
def _execute_query_prepared(
|
||||
self,
|
||||
query: Query,
|
||||
*,
|
||||
batch_size: Optional[int] = None,
|
||||
timeout: Optional[timedelta] = None,
|
||||
) -> pa.RecordBatchReader:
|
||||
if not _is_remote_query_table(self._table):
|
||||
query._blob_row_id_prepared = True
|
||||
return self._table._execute_query(query, batch_size=batch_size, timeout=timeout)
|
||||
|
||||
def _execute_arrow_prepared(
|
||||
self, query: Query, *, timeout: Optional[timedelta] = None
|
||||
) -> pa.Table:
|
||||
if not _is_remote_query_table(self._table):
|
||||
query._blob_row_id_prepared = True
|
||||
return self._table._execute_arrow(query, timeout=timeout)
|
||||
|
||||
def _ensure_fragment_constraints_supported(self, operation: str) -> None:
|
||||
_raise_unsupported_fragment_constraints(
|
||||
self._fragments,
|
||||
@@ -1831,13 +1881,18 @@ class LanceQueryBuilder(ABC):
|
||||
)
|
||||
)
|
||||
|
||||
def _validated_blob_sources(self, blob_mode: BlobMode) -> dict[str, str]:
|
||||
def _validated_blob_sources(
|
||||
self, blob_mode: BlobMode, schema: Optional[pa.Schema] = None
|
||||
) -> dict[str, str]:
|
||||
"""Map projected blob outputs to their source columns.
|
||||
|
||||
Bytes mode is checked here, before the query runs.
|
||||
"""
|
||||
validate_blob_mode(blob_mode)
|
||||
schema = self._table.schema
|
||||
if blob_mode == "lazy":
|
||||
return {}
|
||||
if schema is None:
|
||||
schema = self._table.schema
|
||||
blob_sources = blob_projection_sources(
|
||||
schema,
|
||||
self._columns,
|
||||
@@ -1885,8 +1940,9 @@ class LanceQueryBuilder(ABC):
|
||||
*,
|
||||
blob_mode: BlobMode,
|
||||
blob_sources: dict[str, str],
|
||||
schema: Optional[pa.Schema] = None,
|
||||
) -> pa.Table:
|
||||
blob_auto_row_id = self._blob_auto_row_id_enabled()
|
||||
blob_auto_row_id = self._blob_auto_row_id_enabled(schema)
|
||||
if blob_mode == "bytes" and blob_sources:
|
||||
# Bytes conversion reads _rowid directly, including when the
|
||||
# projection mixes legacy and v2 columns.
|
||||
@@ -1914,22 +1970,26 @@ class LanceQueryBuilder(ABC):
|
||||
reader: pa.RecordBatchReader,
|
||||
blob_mode: BlobMode,
|
||||
blob_sources: dict[str, str],
|
||||
schema: Optional[pa.Schema] = None,
|
||||
) -> pa.RecordBatchReader:
|
||||
if blob_mode == "lazy":
|
||||
return reader
|
||||
|
||||
def convert(tbl: pa.Table) -> pa.Table:
|
||||
return self._finalize_blob_query_table(
|
||||
tbl, blob_mode=blob_mode, blob_sources=blob_sources
|
||||
tbl,
|
||||
blob_mode=blob_mode,
|
||||
blob_sources=blob_sources,
|
||||
schema=schema,
|
||||
)
|
||||
|
||||
schema = convert(pa.Table.from_batches([], schema=reader.schema)).schema
|
||||
result_schema = convert(pa.Table.from_batches([], schema=reader.schema)).schema
|
||||
|
||||
def batches():
|
||||
for batch in reader:
|
||||
yield from convert(pa.Table.from_batches([batch])).to_batches()
|
||||
|
||||
return pa.RecordBatchReader.from_batches(schema, batches())
|
||||
return pa.RecordBatchReader.from_batches(result_schema, batches())
|
||||
|
||||
def with_row_address(self, with_row_address: bool = True) -> Self:
|
||||
"""Set whether to return row addresses.
|
||||
@@ -2566,17 +2626,26 @@ class LanceVectorQueryBuilder(LanceQueryBuilder):
|
||||
``"bytes"`` returns payload bytes for supported row-addressable blob
|
||||
columns and raises for blobs inside lists.
|
||||
"""
|
||||
blob_sources = self._validated_blob_sources(blob_mode)
|
||||
blob_sources, schema = self._prepare_blob_execution(blob_mode)
|
||||
if blob_mode != "lazy":
|
||||
# Materialize in lazy mode so reranking runs once over the full
|
||||
# result before the requested aggregate blob conversion.
|
||||
return self._finalize_blob_query_table(
|
||||
self.to_batches(timeout=timeout).read_all(),
|
||||
self._to_batches_prepared(
|
||||
batch_size=None,
|
||||
timeout=timeout,
|
||||
blob_mode="lazy",
|
||||
blob_sources=blob_sources,
|
||||
schema=schema,
|
||||
).read_all(),
|
||||
blob_mode=blob_mode,
|
||||
blob_sources=blob_sources,
|
||||
schema=schema,
|
||||
)
|
||||
|
||||
self._ensure_fragment_constraints_supported("to_arrow()")
|
||||
results = self._table._execute_arrow(
|
||||
self._query_for_scan(blob_sources), timeout=timeout
|
||||
results = self._execute_arrow_prepared(
|
||||
self._query_for_scan(blob_sources, schema), timeout=timeout
|
||||
)
|
||||
if self._reranker is not None:
|
||||
source = results
|
||||
@@ -2584,7 +2653,10 @@ class LanceVectorQueryBuilder(LanceQueryBuilder):
|
||||
check_reranker_result(results)
|
||||
results = _merge_query_snapshot(results, source)
|
||||
return self._finalize_blob_query_table(
|
||||
results, blob_mode=blob_mode, blob_sources=blob_sources
|
||||
results,
|
||||
blob_mode=blob_mode,
|
||||
blob_sources=blob_sources,
|
||||
schema=schema,
|
||||
)
|
||||
|
||||
def to_query_object(self) -> Query:
|
||||
@@ -2624,6 +2696,31 @@ class LanceVectorQueryBuilder(LanceQueryBuilder):
|
||||
order_by=self._order_by,
|
||||
)
|
||||
|
||||
def _to_batches_prepared(
|
||||
self,
|
||||
*,
|
||||
batch_size: Optional[int],
|
||||
timeout: Optional[timedelta],
|
||||
blob_mode: BlobMode,
|
||||
blob_sources: dict[str, str],
|
||||
schema: Optional[pa.Schema],
|
||||
) -> pa.RecordBatchReader:
|
||||
query = self._query_for_scan(blob_sources, schema)
|
||||
result_set = self._execute_query_prepared(
|
||||
query, batch_size=batch_size, timeout=timeout
|
||||
)
|
||||
if self._reranker is not None:
|
||||
rs_table = result_set.read_all()
|
||||
result_set = self._reranker.rerank_vector(self._str_query, rs_table)
|
||||
check_reranker_result(result_set)
|
||||
result_set = _merge_query_snapshot(result_set, rs_table)
|
||||
# convert result_set back to RecordBatchReader
|
||||
result_set = pa.RecordBatchReader.from_batches(
|
||||
result_set.schema, result_set.to_batches()
|
||||
)
|
||||
|
||||
return self._batches_in_mode(result_set, blob_mode, blob_sources, schema)
|
||||
|
||||
def to_batches(
|
||||
self,
|
||||
/,
|
||||
@@ -2652,25 +2749,14 @@ class LanceVectorQueryBuilder(LanceQueryBuilder):
|
||||
-------
|
||||
pa.RecordBatchReader
|
||||
"""
|
||||
blob_sources = self._validated_blob_sources(blob_mode)
|
||||
vector = self._query if isinstance(self._query, list) else self._query.tolist()
|
||||
if isinstance(vector[0], np.ndarray):
|
||||
vector = [v.tolist() for v in vector]
|
||||
query = self._query_for_scan(blob_sources)
|
||||
result_set = self._table._execute_query(
|
||||
query, batch_size=batch_size, timeout=timeout
|
||||
blob_sources, schema = self._prepare_blob_execution(blob_mode)
|
||||
return self._to_batches_prepared(
|
||||
batch_size=batch_size,
|
||||
timeout=timeout,
|
||||
blob_mode=blob_mode,
|
||||
blob_sources=blob_sources,
|
||||
schema=schema,
|
||||
)
|
||||
if self._reranker is not None:
|
||||
rs_table = result_set.read_all()
|
||||
result_set = self._reranker.rerank_vector(self._str_query, rs_table)
|
||||
check_reranker_result(result_set)
|
||||
result_set = _merge_query_snapshot(result_set, rs_table)
|
||||
# convert result_set back to RecordBatchReader
|
||||
result_set = pa.RecordBatchReader.from_batches(
|
||||
result_set.schema, result_set.to_batches()
|
||||
)
|
||||
|
||||
return self._batches_in_mode(result_set, blob_mode, blob_sources)
|
||||
|
||||
def where(
|
||||
self, where: Union[str, Expr], prefilter: bool = None
|
||||
@@ -2906,22 +2992,25 @@ class LanceFtsQueryBuilder(LanceQueryBuilder):
|
||||
timeout: Optional[timedelta] = None,
|
||||
blob_mode: BlobMode = "lazy",
|
||||
) -> pa.Table:
|
||||
blob_sources = self._validated_blob_sources(blob_mode)
|
||||
blob_sources, schema = self._prepare_blob_execution(blob_mode)
|
||||
self._table._ensure_no_legacy_fts_index()
|
||||
|
||||
self._ensure_fragment_constraints_supported("to_arrow()")
|
||||
query = self._query_for_scan(blob_sources)
|
||||
query = self._query_for_scan(blob_sources, schema)
|
||||
if blob_mode == "lazy":
|
||||
results = self._table._execute_arrow(query, timeout=timeout)
|
||||
results = self._execute_arrow_prepared(query, timeout=timeout)
|
||||
else:
|
||||
results = self._table._execute_query(query, timeout=timeout).read_all()
|
||||
results = self._execute_query_prepared(query, timeout=timeout).read_all()
|
||||
if self._reranker is not None:
|
||||
source = results
|
||||
results = self._reranker.rerank_fts(self._query, results)
|
||||
check_reranker_result(results)
|
||||
results = _merge_query_snapshot(results, source)
|
||||
return self._finalize_blob_query_table(
|
||||
results, blob_mode=blob_mode, blob_sources=blob_sources
|
||||
results,
|
||||
blob_mode=blob_mode,
|
||||
blob_sources=blob_sources,
|
||||
schema=schema,
|
||||
)
|
||||
|
||||
def to_batches(
|
||||
@@ -2960,23 +3049,37 @@ class LanceEmptyQueryBuilder(LanceQueryBuilder):
|
||||
timeout: Optional[timedelta] = None,
|
||||
blob_mode: BlobMode = "lazy",
|
||||
) -> pa.Table:
|
||||
blob_sources = self._validated_blob_sources(blob_mode)
|
||||
blob_sources, schema = self._prepare_blob_execution(blob_mode)
|
||||
if blob_mode == "bytes" and blob_sources:
|
||||
return self.to_batches(timeout=timeout, blob_mode=blob_mode).read_all()
|
||||
return self._to_batches_prepared(
|
||||
batch_size=None,
|
||||
timeout=timeout,
|
||||
blob_mode="bytes",
|
||||
blob_sources=blob_sources,
|
||||
schema=schema,
|
||||
).read_all()
|
||||
if blob_mode != "lazy":
|
||||
return self._finalize_blob_query_table(
|
||||
self.to_batches(timeout=timeout).read_all(),
|
||||
self._to_batches_prepared(
|
||||
batch_size=None,
|
||||
timeout=timeout,
|
||||
blob_mode="lazy",
|
||||
blob_sources=blob_sources,
|
||||
schema=schema,
|
||||
).read_all(),
|
||||
blob_mode=blob_mode,
|
||||
blob_sources=blob_sources,
|
||||
schema=schema,
|
||||
)
|
||||
|
||||
self._ensure_fragment_constraints_supported("to_arrow()")
|
||||
return self._finalize_blob_query_table(
|
||||
self._table._execute_arrow(
|
||||
self._query_for_scan(blob_sources), timeout=timeout
|
||||
self._execute_arrow_prepared(
|
||||
self._query_for_scan(blob_sources, schema), timeout=timeout
|
||||
),
|
||||
blob_mode=blob_mode,
|
||||
blob_sources=blob_sources,
|
||||
schema=schema,
|
||||
)
|
||||
|
||||
def to_query_object(self) -> Query:
|
||||
@@ -3005,12 +3108,14 @@ class LanceEmptyQueryBuilder(LanceQueryBuilder):
|
||||
*,
|
||||
blob_mode: BlobMode = "lazy",
|
||||
) -> pa.RecordBatchReader:
|
||||
blob_sources = self._validated_blob_sources(blob_mode)
|
||||
query = self._query_for_scan(blob_sources)
|
||||
reader = self._table._execute_query(
|
||||
query, batch_size=batch_size, timeout=timeout
|
||||
blob_sources, schema = self._prepare_blob_execution(blob_mode)
|
||||
return self._to_batches_prepared(
|
||||
batch_size=batch_size,
|
||||
timeout=timeout,
|
||||
blob_mode=blob_mode,
|
||||
blob_sources=blob_sources,
|
||||
schema=schema,
|
||||
)
|
||||
return self._batches_in_mode(reader, blob_mode, blob_sources)
|
||||
|
||||
def rerank(self, reranker: Reranker) -> LanceEmptyQueryBuilder:
|
||||
"""Rerank the results using the specified reranker.
|
||||
@@ -3155,11 +3260,14 @@ class LanceHybridQueryBuilder(LanceQueryBuilder):
|
||||
timeout: Optional[timedelta] = None,
|
||||
blob_mode: BlobMode = "lazy",
|
||||
) -> pa.Table:
|
||||
blob_sources = self._validated_blob_sources(blob_mode)
|
||||
blob_sources, schema = self._prepare_blob_execution(blob_mode)
|
||||
# WAL-PK-FUSION: without the fallback, this body is `_run_hybrid`'s.
|
||||
return _wal_hybrid.with_pk_fallback(
|
||||
lambda: self._run_hybrid(
|
||||
timeout=timeout, blob_mode=blob_mode, blob_sources=blob_sources
|
||||
timeout=timeout,
|
||||
blob_mode=blob_mode,
|
||||
blob_sources=blob_sources,
|
||||
schema=schema,
|
||||
),
|
||||
self._table,
|
||||
fused=lambda: self._pk_fusion is not None,
|
||||
@@ -3172,6 +3280,7 @@ class LanceHybridQueryBuilder(LanceQueryBuilder):
|
||||
timeout: Optional[timedelta] = None,
|
||||
blob_mode: BlobMode,
|
||||
blob_sources: dict[str, str],
|
||||
schema: Optional[pa.Schema],
|
||||
) -> pa.Table:
|
||||
self._create_query_builders()
|
||||
fts_query, vector_query = self._fts_query, self._vector_query
|
||||
@@ -3201,7 +3310,10 @@ class LanceHybridQueryBuilder(LanceQueryBuilder):
|
||||
)
|
||||
results = _merge_query_snapshot(results, fts_results, vector_results)
|
||||
return self._finish_hybrid_results(
|
||||
results, blob_mode=blob_mode, blob_sources=blob_sources
|
||||
results,
|
||||
blob_mode=blob_mode,
|
||||
blob_sources=blob_sources,
|
||||
schema=schema,
|
||||
)
|
||||
|
||||
def _finish_hybrid_results(
|
||||
@@ -3210,6 +3322,7 @@ class LanceHybridQueryBuilder(LanceQueryBuilder):
|
||||
*,
|
||||
blob_mode: BlobMode,
|
||||
blob_sources: dict[str, str],
|
||||
schema: Optional[pa.Schema],
|
||||
) -> pa.Table:
|
||||
if self._pk_fusion is not None: # WAL-PK-FUSION: delete.
|
||||
return self._apply_arrow_blob_mode(
|
||||
@@ -3217,9 +3330,12 @@ class LanceHybridQueryBuilder(LanceQueryBuilder):
|
||||
)
|
||||
if self._user_requested_row_id():
|
||||
return self._apply_arrow_blob_mode(results, blob_mode, blob_sources)
|
||||
if self._blob_auto_row_id_enabled():
|
||||
if self._blob_auto_row_id_enabled(schema):
|
||||
return self._finalize_blob_query_table(
|
||||
results, blob_mode=blob_mode, blob_sources=blob_sources
|
||||
results,
|
||||
blob_mode=blob_mode,
|
||||
blob_sources=blob_sources,
|
||||
schema=schema,
|
||||
)
|
||||
if "_rowid" in results.column_names:
|
||||
# Fetch bytes before dropping _rowid.
|
||||
@@ -3853,6 +3969,8 @@ class AsyncQueryBase(object):
|
||||
self._with_row_id = None
|
||||
self._blob_auto_row_id = False
|
||||
self._blob_paths: tuple[str, ...] = ()
|
||||
# Set by the sync table path, which has already prepared blob row ids.
|
||||
self._blob_row_id_prepared = False
|
||||
|
||||
def to_query_object(self) -> Query:
|
||||
"""
|
||||
@@ -3915,6 +4033,26 @@ class AsyncQueryBase(object):
|
||||
self._blob_paths = tuple(blob_v2_projection_sources(schema, projection).keys())
|
||||
self._inner.with_row_id()
|
||||
|
||||
def _maybe_add_blob_row_id_sync(self) -> None:
|
||||
if self._table is None:
|
||||
self._blob_auto_row_id = False
|
||||
self._blob_paths = ()
|
||||
return
|
||||
|
||||
req = self._inner.to_query_request()
|
||||
schema = self._table._schema_sync()
|
||||
projection = _query_request_projection(req)
|
||||
self._blob_auto_row_id = blob_auto_row_id_for_scan(
|
||||
schema,
|
||||
projection,
|
||||
with_row_id=self._with_row_id,
|
||||
)
|
||||
if not self._blob_auto_row_id:
|
||||
self._blob_paths = ()
|
||||
return
|
||||
self._blob_paths = tuple(blob_v2_projection_sources(schema, projection).keys())
|
||||
self._inner.with_row_id()
|
||||
|
||||
async def _can_fetch_plain_legacy_blobs(self, blob_mode: BlobMode) -> bool:
|
||||
if blob_mode != "bytes" or self._table is None:
|
||||
return False
|
||||
@@ -4097,10 +4235,23 @@ class AsyncQueryBase(object):
|
||||
) -> pa.Table:
|
||||
"""Execute with the native eager collector used by ``to_arrow``."""
|
||||
self._ensure_fragment_constraints_supported("to_arrow()")
|
||||
await self._maybe_add_blob_row_id()
|
||||
if not self._blob_row_id_prepared:
|
||||
await self._maybe_add_blob_row_id()
|
||||
reader = await self._inner.execute_to_reader(None, timeout)
|
||||
return pa.Table.from_batches(reader, schema=reader.schema)
|
||||
|
||||
def _execute_eager_sync(
|
||||
self,
|
||||
*,
|
||||
timeout: Optional[timedelta] = None,
|
||||
) -> pa.Table:
|
||||
"""Execute with the synchronous native eager collector."""
|
||||
self._ensure_fragment_constraints_supported("to_arrow()")
|
||||
if not self._blob_row_id_prepared:
|
||||
self._maybe_add_blob_row_id_sync()
|
||||
reader = self._inner.execute_to_reader_sync(None, timeout)
|
||||
return pa.Table.from_batches(reader, schema=reader.schema)
|
||||
|
||||
async def _execute_batches(
|
||||
self,
|
||||
*,
|
||||
@@ -4125,7 +4276,8 @@ class AsyncQueryBase(object):
|
||||
max_batch_length=max_batch_length,
|
||||
timeout=timeout,
|
||||
)
|
||||
await self._maybe_add_blob_row_id()
|
||||
if not self._blob_row_id_prepared:
|
||||
await self._maybe_add_blob_row_id()
|
||||
return AsyncRecordBatchReader(
|
||||
await self._inner.execute(
|
||||
max_batch_length=max_batch_length, timeout=timeout
|
||||
@@ -4998,6 +5150,22 @@ class AsyncFTSQuery(AsyncStandardQuery):
|
||||
results = _merge_query_snapshot(results, source)
|
||||
return results
|
||||
|
||||
def _execute_eager_sync(
|
||||
self,
|
||||
*,
|
||||
timeout: Optional[timedelta] = None,
|
||||
) -> pa.Table:
|
||||
try:
|
||||
results = super()._execute_eager_sync(timeout=timeout)
|
||||
except Exception as error:
|
||||
_add_fts_position_error_note(error)
|
||||
raise
|
||||
if self._reranker:
|
||||
source = results
|
||||
results = self._reranker.rerank_fts(self.get_query(), results)
|
||||
results = _merge_query_snapshot(results, source)
|
||||
return results
|
||||
|
||||
async def _execute_batches(
|
||||
self,
|
||||
*,
|
||||
@@ -5360,6 +5528,18 @@ class AsyncVectorQuery(AsyncStandardQuery, AsyncVectorQueryBase):
|
||||
results = _merge_query_snapshot(results, source)
|
||||
return results
|
||||
|
||||
def _execute_eager_sync(
|
||||
self,
|
||||
*,
|
||||
timeout: Optional[timedelta] = None,
|
||||
) -> pa.Table:
|
||||
results = super()._execute_eager_sync(timeout=timeout)
|
||||
if self._reranker:
|
||||
source = results
|
||||
results = self._reranker.rerank_vector(self._query_string, results)
|
||||
results = _merge_query_snapshot(results, source)
|
||||
return results
|
||||
|
||||
async def _execute_batches(
|
||||
self,
|
||||
*,
|
||||
|
||||
@@ -641,6 +641,8 @@ class RemoteDBConnection(DBConnection):
|
||||
storage_options: Optional[Dict[str, str]] = None,
|
||||
data_storage_version: Optional[str] = None,
|
||||
enable_v2_manifest_paths: Optional[bool] = None,
|
||||
initial_bases: Optional[List[Any]] = None,
|
||||
allow_external_blob_outside_bases: bool = False,
|
||||
) -> Table:
|
||||
"""Create a [Table][lancedb.table.Table] in the database.
|
||||
|
||||
@@ -686,6 +688,10 @@ class RemoteDBConnection(DBConnection):
|
||||
Not supported in LanceDB Enterprise. Raises NotImplementedError.
|
||||
enable_v2_manifest_paths: bool, optional
|
||||
Not supported in LanceDB Enterprise. Raises NotImplementedError.
|
||||
initial_bases: list, optional
|
||||
Not supported in LanceDB Enterprise. Raises NotImplementedError.
|
||||
allow_external_blob_outside_bases: bool, default False
|
||||
Not supported in LanceDB Enterprise. Raises NotImplementedError.
|
||||
|
||||
Returns
|
||||
-------
|
||||
@@ -761,6 +767,16 @@ class RemoteDBConnection(DBConnection):
|
||||
f"{option} is not supported for table creation in "
|
||||
"LanceDB Enterprise"
|
||||
)
|
||||
if initial_bases:
|
||||
raise NotImplementedError(
|
||||
"initial_bases is not supported for table creation in "
|
||||
"LanceDB Enterprise"
|
||||
)
|
||||
if allow_external_blob_outside_bases:
|
||||
raise NotImplementedError(
|
||||
"allow_external_blob_outside_bases is not supported for table "
|
||||
"creation in LanceDB Enterprise"
|
||||
)
|
||||
if exist_ok:
|
||||
if mode == "create":
|
||||
mode = "exist_ok"
|
||||
|
||||
@@ -1556,9 +1556,15 @@ class RemoteTable(Table):
|
||||
return LOOP.run(self._table.uri())
|
||||
|
||||
def take_offsets(
|
||||
self, offsets: list[int], *, with_row_id: bool = False
|
||||
self,
|
||||
offsets: list[int],
|
||||
*,
|
||||
with_row_id: bool = False,
|
||||
preserve_order: bool = False,
|
||||
) -> LanceTakeQueryBuilder:
|
||||
builder = LanceTakeQueryBuilder(self._table.take_offsets(offsets))
|
||||
builder = LanceTakeQueryBuilder(
|
||||
self._table.take_offsets(offsets, preserve_order=preserve_order)
|
||||
)
|
||||
if with_row_id:
|
||||
builder.with_row_id()
|
||||
return builder
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
|
||||
import ctypes
|
||||
import importlib
|
||||
from dataclasses import dataclass
|
||||
from typing import TYPE_CHECKING, Iterable, Optional
|
||||
|
||||
import pyarrow as pa
|
||||
@@ -27,6 +28,78 @@ _BLOB_V2_STORAGE_TYPE = pa.struct(
|
||||
]
|
||||
)
|
||||
_resolved_blob_type = None
|
||||
_UINT32_MAX = 0xFFFF_FFFF
|
||||
_UINT64_MAX = 0xFFFF_FFFF_FFFF_FFFF
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class BasePath:
|
||||
"""A storage base registered on a table at creation time.
|
||||
|
||||
Use with the ``initial_bases`` argument of
|
||||
[create_table][lancedb.db.DBConnection.create_table] to make
|
||||
external blob URIs resolve under a shared prefix: descriptors that fall
|
||||
under ``path`` are stored relative to it instead of as absolute URIs.
|
||||
|
||||
This is a lightweight stand-in for ``lance.DatasetBasePath`` that does
|
||||
not require pylance. Both classes, and equivalent dictionaries, are
|
||||
accepted by the create APIs.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
path:
|
||||
Full URI of the base (for example ``s3://bucket/prefix`` or a
|
||||
``file://`` URI). A blob URI under this prefix is stored relative to
|
||||
it.
|
||||
name:
|
||||
Optional human-readable name for the base.
|
||||
is_dataset_root:
|
||||
Whether the base uses the dataset-root layout. Defaults to ``False``.
|
||||
Bases registered here must leave this ``False``: Lance only resolves
|
||||
external blob URIs against non-root bases.
|
||||
id:
|
||||
Base ID used by scoped storage options such as ``base_<id>.region``.
|
||||
``None`` lets Lance assign a non-zero ID. ``0`` is reserved for
|
||||
absolute (unregistered) URIs and is rejected.
|
||||
|
||||
When supplying IDs for multiple bases, use distinct explicit non-zero
|
||||
IDs. The pinned Lance release can collide when one base uses automatic
|
||||
allocation and another supplies an explicit ID; the create fails, the
|
||||
table name can remain listed but unopenable, and retrying with distinct
|
||||
explicit IDs succeeds. Automatic allocation for every base is
|
||||
supported.
|
||||
"""
|
||||
|
||||
path: str
|
||||
name: Optional[str] = None
|
||||
is_dataset_root: bool = False
|
||||
id: Optional[int] = None
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
if not isinstance(self.path, str):
|
||||
raise TypeError(f"path must be a string, got {type(self.path).__name__}")
|
||||
if not self.path:
|
||||
raise ValueError("path must not be empty")
|
||||
if self.name is not None and not isinstance(self.name, str):
|
||||
raise TypeError(f"name must be a string, got {type(self.name).__name__}")
|
||||
if not isinstance(self.is_dataset_root, bool):
|
||||
raise TypeError(
|
||||
"is_dataset_root must be a bool, got "
|
||||
f"{type(self.is_dataset_root).__name__}"
|
||||
)
|
||||
if self.id is None:
|
||||
return
|
||||
if isinstance(self.id, bool) or not isinstance(self.id, int):
|
||||
raise TypeError(f"id must be an int or None, got {type(self.id).__name__}")
|
||||
if self.id == 0:
|
||||
raise ValueError(
|
||||
"id=0 is reserved for unregistered blob URIs; "
|
||||
"pass id=None to let Lance assign an ID"
|
||||
)
|
||||
if self.id < 0:
|
||||
raise ValueError("id must be a positive integer")
|
||||
if self.id > _UINT32_MAX:
|
||||
raise ValueError("id must fit in a 32-bit unsigned integer")
|
||||
|
||||
|
||||
class _FallbackBlobType(pa.ExtensionType):
|
||||
@@ -344,6 +417,132 @@ def blob_array(payloads: Iterable[Optional[bytes]]) -> pa.ExtensionArray:
|
||||
return pa.ExtensionArray.from_storage(blob_type, storage)
|
||||
|
||||
|
||||
def _blob_uint64(value: object, what: str) -> int:
|
||||
if isinstance(value, bool) or not isinstance(value, int):
|
||||
raise TypeError(f"{what} must be an int, got {type(value).__name__}")
|
||||
if value < 0:
|
||||
raise ValueError(f"{what} must be non-negative")
|
||||
if value > _UINT64_MAX:
|
||||
raise OverflowError(f"{what} must fit in a uint64")
|
||||
return value
|
||||
|
||||
|
||||
def blob_uri_array(
|
||||
uris: Iterable[Optional[str]],
|
||||
*,
|
||||
positions: Optional[Iterable[Optional[int]]] = None,
|
||||
sizes: Optional[Iterable[Optional[int]]] = None,
|
||||
) -> pa.ExtensionArray:
|
||||
"""Build a Lance blob v2 extension array from external URIs.
|
||||
|
||||
Produces the standard four-field blob v2 storage (``data=None``, ``uri``,
|
||||
nullable ``position`` and ``size``) without requiring pylance, so the
|
||||
result can be used directly in Arrow record batches and combined with
|
||||
field metadata such as ``lancedb:logical_type="mp4"``.
|
||||
|
||||
A row without ``position`` and ``size`` references the whole object; a
|
||||
row with both reads exactly that byte range. Register the object prefix
|
||||
with [BasePath][lancedb.schema.BasePath] at table creation to store a
|
||||
matched URI relative to a base, or enable
|
||||
``allow_external_blob_outside_bases`` on the write that inserts the row to
|
||||
keep the absolute URI when no base matches. The opt-in covers that one
|
||||
write; a later ``add()`` must enable it again.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
uris:
|
||||
An iterable of absolute URI strings or ``None`` for a null blob. A
|
||||
URI under a registered base is matched and stored in the descriptor
|
||||
relative to that base. An unmatched URI requires the write that
|
||||
inserts the row to opt in with
|
||||
``allow_external_blob_outside_bases``, and must always be a valid
|
||||
absolute URI.
|
||||
positions:
|
||||
Optional byte offsets, one per URI. Provide together with ``sizes``;
|
||||
each entry is an ``int`` or ``None``. A range requires both fields.
|
||||
sizes:
|
||||
Optional range lengths in bytes, one per URI. Must be positive when
|
||||
``position`` is set.
|
||||
|
||||
Returns
|
||||
-------
|
||||
pa.ExtensionArray
|
||||
external blob values ready to use in Arrow tables or record batches.
|
||||
|
||||
Raises
|
||||
------
|
||||
TypeError
|
||||
If a URI, position, or size has the wrong type.
|
||||
ValueError
|
||||
If lengths differ, only one of ``positions``/``sizes`` is given, a
|
||||
range is incomplete, a size is not positive, or a range is given for
|
||||
a null URI.
|
||||
OverflowError
|
||||
If a position or size does not fit in a uint64.
|
||||
|
||||
Examples
|
||||
--------
|
||||
>>> import pyarrow as pa
|
||||
>>> from lancedb.schema import blob, blob_uri_array
|
||||
>>> schema = pa.schema([blob("video")])
|
||||
>>> videos = blob_uri_array(
|
||||
... ["s3://bucket/a.mp4", "hf://datasets/org/repo@abc/b.mp4"],
|
||||
... positions=[0, 8],
|
||||
... sizes=[4, 4],
|
||||
... )
|
||||
>>> batch = pa.RecordBatch.from_arrays([videos], schema=schema)
|
||||
>>> batch.num_rows
|
||||
2
|
||||
"""
|
||||
uri_list = list(uris)
|
||||
if positions is None and sizes is None:
|
||||
ranges = [(None, None)] * len(uri_list)
|
||||
elif positions is None or sizes is None:
|
||||
raise ValueError("positions and sizes must be provided together")
|
||||
else:
|
||||
position_list = list(positions)
|
||||
size_list = list(sizes)
|
||||
if len(position_list) != len(uri_list):
|
||||
raise ValueError(
|
||||
"positions must have the same length as uris, got "
|
||||
f"{len(position_list)} and {len(uri_list)}"
|
||||
)
|
||||
if len(size_list) != len(uri_list):
|
||||
raise ValueError(
|
||||
"sizes must have the same length as uris, got "
|
||||
f"{len(size_list)} and {len(uri_list)}"
|
||||
)
|
||||
ranges = list(zip(position_list, size_list, strict=True))
|
||||
|
||||
descriptors = []
|
||||
for index, (uri, (position, size)) in enumerate(zip(uri_list, ranges, strict=True)):
|
||||
if uri is None:
|
||||
if position is not None or size is not None:
|
||||
raise ValueError(
|
||||
f"uris[{index}] is None but a position or size was provided"
|
||||
)
|
||||
descriptors.append(None)
|
||||
continue
|
||||
if not isinstance(uri, str):
|
||||
raise TypeError(f"uris[{index}] must be a string, got {type(uri).__name__}")
|
||||
if position is None and size is None:
|
||||
descriptors.append({"uri": uri})
|
||||
continue
|
||||
if position is None or size is None:
|
||||
raise ValueError(
|
||||
f"uris[{index}] must set both position and size or neither"
|
||||
)
|
||||
position = _blob_uint64(position, f"positions[{index}]")
|
||||
size = _blob_uint64(size, f"sizes[{index}]")
|
||||
if size == 0:
|
||||
raise ValueError(f"sizes[{index}] must be positive to read a byte range")
|
||||
descriptors.append({"uri": uri, "position": position, "size": size})
|
||||
|
||||
blob_type = _resolve_blob_type()()
|
||||
storage = pa.array(descriptors, type=blob_type.storage_type)
|
||||
return pa.ExtensionArray.from_storage(blob_type, storage)
|
||||
|
||||
|
||||
def vector(dimension: int, value_type: pa.DataType = pa.float32()) -> pa.DataType:
|
||||
"""A help function to create a vector type.
|
||||
|
||||
|
||||
+125
-14
@@ -2660,7 +2660,11 @@ class Table(ABC):
|
||||
|
||||
@abstractmethod
|
||||
def take_offsets(
|
||||
self, offsets: list[int], *, with_row_id: bool = False
|
||||
self,
|
||||
offsets: list[int],
|
||||
*,
|
||||
with_row_id: bool = False,
|
||||
preserve_order: bool = False,
|
||||
) -> LanceTakeQueryBuilder:
|
||||
"""
|
||||
Take a list of offsets from the table.
|
||||
@@ -2672,9 +2676,13 @@ class Table(ABC):
|
||||
Offsets are mostly useful for sampling as the set of all valid offsets is easily
|
||||
known in advance to be [0, len(table)).
|
||||
|
||||
No guarantees are made regarding the order in which results are returned.
|
||||
Repeated offsets produce repeated rows, which makes this method suitable for
|
||||
sampling with replacement.
|
||||
By default, no guarantees are made regarding the order in which results
|
||||
are returned. Repeated offsets produce repeated rows, which makes this
|
||||
method suitable for sampling with replacement. Set ``preserve_order=True``
|
||||
to return found rows in input order, including repeated offsets. Missing
|
||||
non-negative offsets are omitted. Negative offsets are rejected and are
|
||||
not Python-style relative indices. ``preserve_order`` cannot be combined
|
||||
with an explicit ``order_by``.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
@@ -2682,6 +2690,10 @@ class Table(ABC):
|
||||
The offsets to take.
|
||||
with_row_id: bool, default False
|
||||
If True, include the "_rowid" column in the results.
|
||||
preserve_order: bool, default False
|
||||
If True, return found rows in input order. Rust take queries apply
|
||||
limit/offset after restoration; Python take builders and Query
|
||||
conversion do not expose pagination.
|
||||
|
||||
Returns
|
||||
-------
|
||||
@@ -2802,6 +2814,15 @@ class Table(ABC):
|
||||
One missing or deleted row ID rejects the entire batch; no partial
|
||||
results are returned.
|
||||
|
||||
A query result table that carries snapshot metadata keeps the snapshot
|
||||
that produced it on LanceDB Enterprise. A query result without that
|
||||
metadata, including a legacy query response, and a plain list are read
|
||||
from the table's current snapshot; keep the source unchanged between
|
||||
selection and fetching. Partial snapshot metadata is rejected. Row
|
||||
positions are not row IDs: to read by position, call
|
||||
``table.take_offsets(offsets, with_row_id=True)`` first and pass the
|
||||
resulting ``_rowid`` values.
|
||||
|
||||
Blobs inside lists cannot be fetched by row id yet.
|
||||
|
||||
LanceDB Enterprise limits each request to 1024 row IDs and 64 MiB of blob
|
||||
@@ -2868,6 +2889,17 @@ class Table(ABC):
|
||||
row ids.
|
||||
One missing or deleted row ID rejects the entire batch; no partial
|
||||
handles are returned.
|
||||
|
||||
A query result table that carries snapshot metadata keeps the snapshot
|
||||
that produced it on LanceDB Enterprise, so every returned handle reads
|
||||
that snapshot. Metadata-free query results, including legacy server
|
||||
responses, and plain lists are read from the table's current snapshot.
|
||||
Partial snapshot metadata is rejected. A snapshot-bound handle fails
|
||||
explicitly when the serving node cannot echo the query snapshot
|
||||
identity; the 0.5.0 floor covers the basic remote Blob API but not that
|
||||
echo. Row positions are not row IDs: call
|
||||
``table.take_offsets(offsets, with_row_id=True)`` first and pass the
|
||||
resulting ``_rowid`` values.
|
||||
"""
|
||||
|
||||
@abstractmethod
|
||||
@@ -4501,7 +4533,10 @@ class LanceTable(Table):
|
||||
-------
|
||||
pa.Schema
|
||||
A PyArrow schema object."""
|
||||
return LOOP.run(self._table.schema())
|
||||
schema_sync = getattr(self._table, "_schema_sync", None)
|
||||
if schema_sync is None:
|
||||
return LOOP.run(self._table.schema())
|
||||
return schema_sync()
|
||||
|
||||
def list_versions(self) -> List[Dict[str, Any]]:
|
||||
"""List all versions of the table"""
|
||||
@@ -4513,9 +4548,15 @@ class LanceTable(Table):
|
||||
return LOOP.run(self._table.version())
|
||||
|
||||
def take_offsets(
|
||||
self, offsets: list[int], *, with_row_id: bool = False
|
||||
self,
|
||||
offsets: list[int],
|
||||
*,
|
||||
with_row_id: bool = False,
|
||||
preserve_order: bool = False,
|
||||
) -> LanceTakeQueryBuilder:
|
||||
builder = LanceTakeQueryBuilder(self._table.take_offsets(offsets))
|
||||
builder = LanceTakeQueryBuilder(
|
||||
self._table.take_offsets(offsets, preserve_order=preserve_order)
|
||||
)
|
||||
if with_row_id:
|
||||
builder.with_row_id()
|
||||
return builder
|
||||
@@ -5727,8 +5768,16 @@ class LanceTable(Table):
|
||||
"""
|
||||
if isinstance(query, FullTextQuery):
|
||||
query_type = "fts"
|
||||
if (
|
||||
vector_column_name is None
|
||||
and query_type != "fts"
|
||||
and not (query is None and query_type != "hybrid")
|
||||
):
|
||||
schema = self.schema
|
||||
else:
|
||||
schema = None
|
||||
vector_column_name = infer_vector_column_name(
|
||||
schema=self.schema,
|
||||
schema=schema,
|
||||
query_type=query_type,
|
||||
query=query,
|
||||
vector_column_name=vector_column_name,
|
||||
@@ -5766,6 +5815,8 @@ class LanceTable(Table):
|
||||
namespace_client: Optional[Any] = None,
|
||||
pushdown_operations: Optional[set] = None,
|
||||
route_pushdown_to_rust: bool = False,
|
||||
initial_bases: Optional[List[Any]] = None,
|
||||
allow_external_blob_outside_bases: bool = False,
|
||||
):
|
||||
"""
|
||||
Create a new table.
|
||||
@@ -5819,6 +5870,20 @@ class LanceTable(Table):
|
||||
enable_v2_manifest_paths: optional, bool, default False
|
||||
Deprecated. Set `storage_options` when connecting to the database and set
|
||||
`new_table_enable_v2_manifest_paths` in the options.
|
||||
initial_bases: list, optional
|
||||
Storage bases to register in the table's manifest in the same
|
||||
commit that creates it. Each entry can be a
|
||||
[BasePath][lancedb.schema.BasePath], a dict with `path`, `name`,
|
||||
`is_dataset_root`, and `id` keys, or a `lance.DatasetBasePath`.
|
||||
Blob URIs under a registered base are stored relative to it. When
|
||||
supplying IDs for multiple bases, use distinct explicit non-zero
|
||||
IDs; [BasePath][lancedb.schema.BasePath] describes the pinned-Lance
|
||||
limitation.
|
||||
allow_external_blob_outside_bases: bool, default False
|
||||
Store blob URIs that do not fall under a registered base. The row
|
||||
keeps a reference, so the objects have to stay readable. The
|
||||
opt-in applies only to the initial data; a later `add()` must
|
||||
enable it again.
|
||||
"""
|
||||
if namespace_path is None:
|
||||
namespace_path = []
|
||||
@@ -5870,6 +5935,8 @@ class LanceTable(Table):
|
||||
storage_options=storage_options,
|
||||
location=location,
|
||||
namespace_client=namespace_client,
|
||||
initial_bases=initial_bases,
|
||||
allow_external_blob_outside_bases=allow_external_blob_outside_bases,
|
||||
)
|
||||
)
|
||||
self._branch = self._table.current_branch()
|
||||
@@ -5995,6 +6062,14 @@ class LanceTable(Table):
|
||||
return self._execute_query(query, timeout=timeout).read_all()
|
||||
|
||||
async_query = self._table._sync_query_to_async(query)
|
||||
async_query._blob_row_id_prepared = query._blob_row_id_prepared
|
||||
if (
|
||||
self._table._inner._is_native()
|
||||
and self._namespace_client is None
|
||||
and not self._route_pushdown_to_rust
|
||||
and isinstance(async_query, (AsyncQuery, AsyncVectorQuery, AsyncFTSQuery))
|
||||
):
|
||||
return async_query._execute_eager_sync(timeout=timeout)
|
||||
return LOOP.run(async_query._execute_eager(timeout=timeout))
|
||||
|
||||
def _explain_plan(self, query: Query, verbose: Optional[bool] = False) -> str:
|
||||
@@ -7365,6 +7440,9 @@ class AsyncTable:
|
||||
"""
|
||||
return _restore_blob_extensions(await self._inner.schema())
|
||||
|
||||
def _schema_sync(self) -> pa.Schema:
|
||||
return _restore_blob_extensions(self._inner.schema_sync())
|
||||
|
||||
async def embedding_functions(self) -> Dict[str, EmbeddingFunctionConfig]:
|
||||
"""
|
||||
Get the embedding functions for the table
|
||||
@@ -8402,10 +8480,18 @@ class AsyncTable:
|
||||
if query.take_offsets is not None or query.take_row_ids is not None:
|
||||
if query.take_offsets is not None and query.take_row_ids is not None:
|
||||
raise ValueError("Only one of take_offsets and take_row_ids may be set")
|
||||
if query.preserve_order is True and query.take_offsets is None:
|
||||
raise ValueError("preserve_order only supports take_offsets")
|
||||
if query.preserve_order is True and query.order_by:
|
||||
raise ValueError(
|
||||
"preserve_order cannot be combined with an explicit order_by"
|
||||
)
|
||||
take_query = (
|
||||
self.take_row_ids(query.take_row_ids)
|
||||
if query.take_row_ids is not None
|
||||
else self.take_offsets(query.take_offsets)
|
||||
else self.take_offsets(
|
||||
query.take_offsets, preserve_order=query.preserve_order is True
|
||||
)
|
||||
)
|
||||
if query.columns is not None:
|
||||
columns = query.columns
|
||||
@@ -8509,6 +8595,7 @@ class AsyncTable:
|
||||
# used for that code path right now.
|
||||
|
||||
async_query = self._sync_query_to_async(query)
|
||||
async_query._blob_row_id_prepared = query._blob_row_id_prepared
|
||||
|
||||
return await async_query.to_batches(
|
||||
max_batch_length=batch_size, timeout=timeout
|
||||
@@ -8530,6 +8617,7 @@ class AsyncTable:
|
||||
return (await self._execute_query(query, timeout=timeout)).read_all()
|
||||
|
||||
async_query = self._sync_query_to_async(query)
|
||||
async_query._blob_row_id_prepared = query._blob_row_id_prepared
|
||||
return await async_query._execute_eager(timeout=timeout)
|
||||
|
||||
async def _explain_plan(self, query: Query, verbose: Optional[bool]) -> str:
|
||||
@@ -9613,7 +9701,11 @@ class AsyncTable:
|
||||
await self._inner.restore(version)
|
||||
|
||||
def take_offsets(
|
||||
self, offsets: list[int], *, with_row_id: bool = False
|
||||
self,
|
||||
offsets: list[int],
|
||||
*,
|
||||
with_row_id: bool = False,
|
||||
preserve_order: bool = False,
|
||||
) -> AsyncTakeQuery:
|
||||
"""
|
||||
Take a list of offsets from the table.
|
||||
@@ -9625,8 +9717,12 @@ class AsyncTable:
|
||||
Offsets are mostly useful for sampling as the set of all valid offsets is easily
|
||||
known in advance to be [0, len(table)).
|
||||
|
||||
No guarantees are made regarding the order in which results are returned.
|
||||
Repeated offsets produce repeated rows.
|
||||
By default, no guarantees are made regarding the order in which results
|
||||
are returned. Repeated offsets produce repeated rows. Set
|
||||
``preserve_order=True`` to return found rows in input order, including
|
||||
repeated offsets. Missing non-negative offsets are omitted. Negative
|
||||
offsets are rejected and are not Python-style relative indices.
|
||||
``preserve_order`` cannot be combined with an explicit ``order_by``.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
@@ -9634,6 +9730,10 @@ class AsyncTable:
|
||||
The offsets to take.
|
||||
with_row_id: bool, default False
|
||||
If True, include the "_rowid" column in the results.
|
||||
preserve_order: bool, default False
|
||||
If True, return found rows in input order. Rust take queries apply
|
||||
limit/offset after restoration; Python take builders and Query
|
||||
conversion do not expose pagination.
|
||||
|
||||
Returns
|
||||
-------
|
||||
@@ -9642,6 +9742,8 @@ class AsyncTable:
|
||||
offsets.
|
||||
"""
|
||||
query = AsyncTakeQuery(self._inner.take_offsets(offsets), self)
|
||||
if preserve_order:
|
||||
query._inner.preserve_order()
|
||||
if with_row_id:
|
||||
query.with_row_id()
|
||||
return query
|
||||
@@ -9693,8 +9795,12 @@ class AsyncTable:
|
||||
column: str,
|
||||
row_ids: Union[list[int], pa.Array, pa.ChunkedArray, pa.Table],
|
||||
) -> pa.LargeBinaryArray:
|
||||
selection = _normalize_blob_row_ids(row_ids, column)
|
||||
return await self._inner.fetch_blobs(
|
||||
column, _normalize_blob_row_ids(row_ids, column)
|
||||
column,
|
||||
selection.row_ids,
|
||||
version=selection.version,
|
||||
snapshot_identity=selection.snapshot_identity,
|
||||
)
|
||||
|
||||
async def fetch_blob_ranges(
|
||||
@@ -9720,8 +9826,13 @@ class AsyncTable:
|
||||
See [Table.fetch_blob_files][lancedb.table.Table.fetch_blob_files].
|
||||
"""
|
||||
buffer_size = _validate_blob_buffer_size(buffer_size)
|
||||
selection = _normalize_blob_row_ids(row_ids, column)
|
||||
handles = await self._inner.fetch_blob_files(
|
||||
column, _normalize_blob_row_ids(row_ids, column), buffer_size
|
||||
column,
|
||||
selection.row_ids,
|
||||
buffer_size=buffer_size,
|
||||
version=selection.version,
|
||||
snapshot_identity=selection.snapshot_identity,
|
||||
)
|
||||
return _wrap_blob_files(handles)
|
||||
|
||||
|
||||
+332
-32
@@ -8,9 +8,11 @@ import importlib
|
||||
import math
|
||||
import os
|
||||
import pathlib
|
||||
import sys
|
||||
import warnings
|
||||
from datetime import date, datetime, time, timedelta
|
||||
from decimal import Decimal
|
||||
from enum import Enum
|
||||
from functools import singledispatch
|
||||
from typing import Tuple, Union, Optional, Any, List
|
||||
from urllib.parse import urlparse
|
||||
@@ -328,7 +330,7 @@ def _query_vector_dim(query: Optional[Any]) -> Optional[int]:
|
||||
|
||||
|
||||
def infer_vector_column_name(
|
||||
schema: pa.Schema,
|
||||
schema: Optional[pa.Schema],
|
||||
query_type: str,
|
||||
query: Optional[Any], # inferred later in query builder
|
||||
vector_column_name: Optional[str],
|
||||
@@ -348,6 +350,8 @@ def infer_vector_column_name(
|
||||
# nothing to infer.
|
||||
return None
|
||||
|
||||
if schema is None:
|
||||
raise ValueError("schema is required to infer a vector column")
|
||||
vector_column_name = inf_vector_column_query(schema, dim=_query_vector_dim(query))
|
||||
|
||||
if vector_column_name is None:
|
||||
@@ -382,7 +386,8 @@ def _(value: bytes):
|
||||
|
||||
@value_to_sql.register(int)
|
||||
def _(value: int):
|
||||
return str(value)
|
||||
# int() first: str() of an int-valued Enum member is its name, e.g. "P.HIGH".
|
||||
return str(int(value))
|
||||
|
||||
|
||||
@value_to_sql.register(float)
|
||||
@@ -394,7 +399,7 @@ def _(value: float):
|
||||
return (
|
||||
"CAST('Infinity' AS DOUBLE)" if value > 0 else "CAST('-Infinity' AS DOUBLE)"
|
||||
)
|
||||
return str(value)
|
||||
return str(float(value))
|
||||
|
||||
|
||||
@value_to_sql.register(Decimal)
|
||||
@@ -415,6 +420,12 @@ def _(value: type(None)):
|
||||
return "NULL"
|
||||
|
||||
|
||||
@value_to_sql.register(Enum)
|
||||
def _(value: Enum):
|
||||
# Write the member's value, as model_to_dict does for a LanceModel field.
|
||||
return value_to_sql(value.value)
|
||||
|
||||
|
||||
@value_to_sql.register(datetime)
|
||||
def _(value: datetime):
|
||||
return f"'{value.isoformat()}'"
|
||||
@@ -601,15 +612,253 @@ def tbl_to_tensor(tbl: pa.Table):
|
||||
return torch.stack([to_tensor(tbl.column(i)) for i in range(tbl.num_columns)])
|
||||
|
||||
|
||||
_BFLOAT16_EXTENSION_NAME = "lance.bfloat16"
|
||||
_ARROW_EXTENSION_NAME_KEY = "ARROW:extension:name"
|
||||
|
||||
|
||||
def _field_metadata_value(field: pa.Field, key: str):
|
||||
metadata = field.metadata or {}
|
||||
value = metadata.get(key.encode()) or metadata.get(key)
|
||||
if isinstance(value, bytes):
|
||||
return value.decode()
|
||||
return value
|
||||
|
||||
|
||||
def _field_extension_name(field: pa.Field) -> Optional[str]:
|
||||
extension_name = _field_metadata_value(field, _ARROW_EXTENSION_NAME_KEY)
|
||||
if extension_name is not None:
|
||||
return extension_name
|
||||
if isinstance(field.type, pa.ExtensionType):
|
||||
return field.type.extension_name
|
||||
return None
|
||||
|
||||
|
||||
def _field_storage_type(field: pa.Field) -> pa.DataType:
|
||||
if isinstance(field.type, pa.ExtensionType):
|
||||
return field.type.storage_type
|
||||
return field.type
|
||||
|
||||
|
||||
def _is_bfloat16_field(field: pa.Field) -> bool:
|
||||
if _field_extension_name(field) != _BFLOAT16_EXTENSION_NAME:
|
||||
return False
|
||||
storage_type = _field_storage_type(field)
|
||||
return pa.types.is_fixed_size_binary(storage_type) and storage_type.byte_width == 2
|
||||
|
||||
|
||||
def _check_torch_nulls(array: pa.Array, column_name: str) -> None:
|
||||
if array.null_count:
|
||||
raise ValueError(
|
||||
f"Cannot convert column `{column_name}` to a torch tensor because it "
|
||||
f"contains {array.null_count} null value(s). Drop or fill nulls before "
|
||||
"using a torch format."
|
||||
)
|
||||
|
||||
|
||||
def _bfloat16_to_tensor(array: pa.Array, torch, column_name: str):
|
||||
storage = array.storage if isinstance(array.type, pa.ExtensionType) else array
|
||||
storage_type = storage.type
|
||||
if not (
|
||||
pa.types.is_fixed_size_binary(storage_type) and storage_type.byte_width == 2
|
||||
):
|
||||
raise ValueError(
|
||||
f"Column `{column_name}` is marked as {_BFLOAT16_EXTENSION_NAME!r} but "
|
||||
f"has storage type {storage_type}. The lance.bfloat16 extension requires "
|
||||
"fixed_size_binary[2] storage."
|
||||
)
|
||||
_check_torch_nulls(storage, column_name)
|
||||
if len(storage) == 0:
|
||||
return torch.empty((0,), dtype=torch.bfloat16)
|
||||
|
||||
buffer = storage.buffers()[1]
|
||||
if buffer is None:
|
||||
return torch.empty((0,), dtype=torch.bfloat16)
|
||||
offset = storage.offset * 2
|
||||
byte_length = len(storage) * 2
|
||||
if buffer.size < offset + byte_length:
|
||||
raise ValueError(
|
||||
f"Column `{column_name}` has a truncated bfloat16 value buffer."
|
||||
)
|
||||
|
||||
# Arrow stores bfloat16 as two little-endian bytes. Copy only on big-endian
|
||||
# hosts before viewing the same bits as torch.bfloat16.
|
||||
values = np.frombuffer(
|
||||
buffer, dtype=np.dtype("<u2"), count=len(storage), offset=offset
|
||||
)
|
||||
if sys.byteorder != "little":
|
||||
values = values.astype(np.uint16)
|
||||
# Older torch releases cannot create a tensor from np.uint16, so view the
|
||||
# same bits as signed 16-bit values before interpreting them as bfloat16.
|
||||
with warnings.catch_warnings():
|
||||
warnings.filterwarnings(
|
||||
"ignore",
|
||||
message="The given NumPy array is not writable",
|
||||
category=UserWarning,
|
||||
)
|
||||
return torch.from_numpy(values.view(np.int16)).view(torch.bfloat16)
|
||||
|
||||
|
||||
def _leaf_to_tensor(array: pa.Array, field: pa.Field, torch, column_name: str):
|
||||
_check_torch_nulls(array, column_name)
|
||||
if _is_bfloat16_field(field):
|
||||
return _bfloat16_to_tensor(array, torch, column_name)
|
||||
|
||||
data_type = array.type
|
||||
if isinstance(data_type, pa.ExtensionType):
|
||||
raise ValueError(
|
||||
f"Unsupported PyTorch column type {data_type} for column "
|
||||
f"`{column_name}`. Supported extension types are "
|
||||
f"{_BFLOAT16_EXTENSION_NAME!r} and arrow.fixed_shape_tensor."
|
||||
)
|
||||
if (
|
||||
pa.types.is_boolean(data_type)
|
||||
or pa.types.is_integer(data_type)
|
||||
or pa.types.is_floating(data_type)
|
||||
):
|
||||
# Arrow packs booleans as bits while torch uses one byte per value, so
|
||||
# boolean columns always need a copy. Other numeric columns share the
|
||||
# Arrow buffer.
|
||||
zero_copy_only = not pa.types.is_boolean(data_type)
|
||||
try:
|
||||
numpy_values = array.to_numpy(zero_copy_only=zero_copy_only)
|
||||
except pa.ArrowInvalid as err:
|
||||
raise ValueError(
|
||||
f"Cannot convert column `{column_name}` of type {data_type} to a "
|
||||
f"torch tensor without copying: {err}"
|
||||
) from err
|
||||
try:
|
||||
with warnings.catch_warnings():
|
||||
warnings.filterwarnings(
|
||||
"ignore",
|
||||
message="The given NumPy array is not writable",
|
||||
category=UserWarning,
|
||||
)
|
||||
return torch.from_numpy(numpy_values)
|
||||
except (TypeError, RuntimeError) as err:
|
||||
raise ValueError(
|
||||
f"Cannot convert column `{column_name}` of type {data_type} to a "
|
||||
f"torch tensor: {err}"
|
||||
) from err
|
||||
if pa.types.is_fixed_size_binary(data_type) and data_type.byte_width == 2:
|
||||
raise ValueError(
|
||||
f"Column `{column_name}` has type fixed_size_binary[2] but is not "
|
||||
f"marked with {_ARROW_EXTENSION_NAME_KEY!r} = "
|
||||
f"{_BFLOAT16_EXTENSION_NAME!r}. An unmarked binary column is not "
|
||||
"treated as bfloat16."
|
||||
)
|
||||
raise ValueError(
|
||||
f"Unsupported PyTorch column type {data_type} for column `{column_name}`. "
|
||||
"Supported leaf types are boolean, integer, floating point, and "
|
||||
f"{_BFLOAT16_EXTENSION_NAME!r} fixed_size_binary[2] values."
|
||||
)
|
||||
|
||||
|
||||
def _fixed_size_list_to_tensor(array: pa.FixedSizeListArray, torch, column_name: str):
|
||||
_check_torch_nulls(array, column_name)
|
||||
width = array.type.list_size
|
||||
values = array.values.slice(array.offset * width, len(array) * width)
|
||||
child_tensor = _arrow_column_to_tensor(
|
||||
values, array.type.value_field, torch, column_name
|
||||
)
|
||||
return child_tensor.reshape((len(array), width, *child_tensor.shape[1:]))
|
||||
|
||||
|
||||
def _fixed_shape_tensor_to_tensor(array: pa.Array, torch, column_name: str):
|
||||
_check_torch_nulls(array, column_name)
|
||||
tensor_type = array.type
|
||||
storage = array.storage
|
||||
physical_shape = list(tensor_type.shape)
|
||||
permutation = list(getattr(tensor_type, "permutation", None) or [])
|
||||
storage_tensor = _arrow_column_to_tensor(
|
||||
storage, storage.type.value_field, torch, column_name
|
||||
)
|
||||
tensor = storage_tensor.reshape((len(array), *physical_shape))
|
||||
if permutation:
|
||||
# Arrow's ``shape`` is the physical row-major shape, and
|
||||
# ``permutation`` maps a logical axis to its physical axis. Transposing
|
||||
# by it restores the logical shape as a view.
|
||||
tensor = tensor.permute([0] + [axis + 1 for axis in permutation])
|
||||
return tensor
|
||||
|
||||
|
||||
def _arrow_column_to_tensor(array: pa.Array, field: pa.Field, torch, column_name: str):
|
||||
if isinstance(array.type, pa.FixedShapeTensorType):
|
||||
return _fixed_shape_tensor_to_tensor(array, torch, column_name)
|
||||
if pa.types.is_fixed_size_list(array.type):
|
||||
return _fixed_size_list_to_tensor(array, torch, column_name)
|
||||
return _leaf_to_tensor(array, field, torch, column_name).reshape((len(array),))
|
||||
|
||||
|
||||
def _is_nullable_numeric_scalar(array: pa.Array) -> bool:
|
||||
data_type = array.type
|
||||
if isinstance(data_type, pa.ExtensionType) or array.null_count == 0:
|
||||
return False
|
||||
return pa.types.is_integer(data_type) or pa.types.is_floating(data_type)
|
||||
|
||||
|
||||
def _nullable_numeric_scalar_to_tensor(array: pa.Array, torch, column_name: str):
|
||||
try:
|
||||
numpy_values = array.to_numpy(zero_copy_only=False)
|
||||
except pa.ArrowInvalid as err:
|
||||
raise ValueError(
|
||||
f"Cannot convert nullable column `{column_name}` of type {array.type} "
|
||||
f"to a torch tensor: {err}"
|
||||
) from err
|
||||
try:
|
||||
return torch.from_numpy(numpy_values)
|
||||
except (TypeError, RuntimeError) as err:
|
||||
raise ValueError(
|
||||
f"Cannot convert nullable column `{column_name}` of type {array.type} "
|
||||
f"to a torch tensor: {err}"
|
||||
) from err
|
||||
|
||||
|
||||
def _batch_column_tensors(batch: pa.RecordBatch, allow_scalar_nulls: bool = False):
|
||||
torch = attempt_import_or_raise("torch", "torch")
|
||||
columns = []
|
||||
for field, column in zip(batch.schema, batch.columns):
|
||||
if allow_scalar_nulls and _is_nullable_numeric_scalar(column):
|
||||
tensor = _nullable_numeric_scalar_to_tensor(column, torch, field.name)
|
||||
else:
|
||||
tensor = _arrow_column_to_tensor(column, field, torch, field.name)
|
||||
columns.append((field.name, tensor))
|
||||
return torch, columns
|
||||
|
||||
|
||||
def _uniform_column_tensors(
|
||||
batch: pa.RecordBatch, format_name: str, allow_scalar_nulls: bool = False
|
||||
):
|
||||
torch, columns = _batch_column_tensors(batch, allow_scalar_nulls=allow_scalar_nulls)
|
||||
if len(columns) <= 1:
|
||||
return torch, columns
|
||||
|
||||
first_name, first = columns[0]
|
||||
first_shape = tuple(first.shape[1:])
|
||||
for name, tensor in columns[1:]:
|
||||
shape = tuple(tensor.shape[1:])
|
||||
if shape != first_shape:
|
||||
raise ValueError(
|
||||
f"Cannot use the {format_name!r} format because column `{name}` "
|
||||
f"has sample shape {shape} while column `{first_name}` has sample "
|
||||
f'shape {first_shape}. Use with_format("torch_dict") for columns '
|
||||
'with different shapes, or with_format("torch") for a list of '
|
||||
"per-row dicts."
|
||||
)
|
||||
return torch, columns
|
||||
|
||||
|
||||
def batch_to_tensor(batch: pa.RecordBatch):
|
||||
"""
|
||||
Convert a PyArrow RecordBatch to a PyTorch Tensor.
|
||||
|
||||
Each column is converted to a tensor (using zero-copy via DLPack)
|
||||
and the columns are then stacked into a single tensor.
|
||||
Each column is converted to a tensor with shape ``(rows, *sample_shape)``
|
||||
and the columns are stacked along a new leading dimension. Scalar columns
|
||||
have sample shape ``()`` and fixed-size-list columns contribute each list
|
||||
dimension. All columns must have the same sample shape.
|
||||
|
||||
Fails if torch is not installed.
|
||||
Fails if a column's data type is not supported by PyTorch.
|
||||
Fails if a column contains nulls.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
@@ -618,43 +867,99 @@ def batch_to_tensor(batch: pa.RecordBatch):
|
||||
|
||||
Returns
|
||||
-------
|
||||
torch.Tensor: The tensor containing the columns of the record batch.
|
||||
torch.Tensor: A tensor with shape ``(columns, rows, *sample_shape)``. A
|
||||
one-column batch returns an ``unsqueeze(0)`` view of that column.
|
||||
"""
|
||||
torch = attempt_import_or_raise("torch", "torch")
|
||||
return torch.stack([torch.from_dlpack(col) for col in batch.columns])
|
||||
torch, columns = _uniform_column_tensors(batch, "torch_col")
|
||||
if not columns:
|
||||
return torch.empty((0, batch.num_rows))
|
||||
if len(columns) == 1:
|
||||
return columns[0][1].unsqueeze(0)
|
||||
return torch.stack([tensor for _, tensor in columns], dim=0)
|
||||
|
||||
|
||||
def batch_to_tensor_rows(batch: pa.RecordBatch):
|
||||
"""
|
||||
Convert a PyArrow RecordBatch to a list of PyTorch Tensor, one per row
|
||||
Convert a PyArrow RecordBatch to a list of PyTorch Tensors, one per row.
|
||||
|
||||
Each column is converted to a tensor (using zero-copy via DLPack)
|
||||
and the columns are then stacked into a single tensor. The 2D tensor
|
||||
is then converted to a list of tensors, one per row
|
||||
Each row tensor has shape ``(columns, *sample_shape)``. All columns must
|
||||
have the same sample shape, so a table mixing scalar and vector columns
|
||||
should use ``torch_dict`` or ``torch`` instead. Dtypes are combined with
|
||||
``torch.promote_types``, matching PyTorch's numeric promotion rules.
|
||||
|
||||
Fails if torch or numpy is not installed.
|
||||
Fails if torch is not installed.
|
||||
Fails if a column's data type is not supported by PyTorch.
|
||||
Nulls in ordinary integer or floating scalar columns become ``NaN``.
|
||||
Nulls in nested fixed-size-list or tensor columns are rejected.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
batch : pa.RecordBatch
|
||||
The record batch to convert.
|
||||
|
||||
Returns
|
||||
-------
|
||||
list[torch.Tensor]
|
||||
One tensor per row, each with shape ``(columns, *sample_shape)``. A
|
||||
one-column scalar batch produces ``(1,)`` tensors.
|
||||
"""
|
||||
torch = attempt_import_or_raise("torch", "torch")
|
||||
numpy = attempt_import_or_raise("numpy", "numpy")
|
||||
columns = [col.to_numpy(zero_copy_only=False) for col in batch.columns]
|
||||
stacked = torch.tensor(numpy.column_stack(columns))
|
||||
rows = list(stacked.unbind(dim=0))
|
||||
return rows
|
||||
torch, columns = _uniform_column_tensors(
|
||||
batch, "torch_row", allow_scalar_nulls=True
|
||||
)
|
||||
if not columns:
|
||||
return [torch.empty((0,)) for _ in range(batch.num_rows)]
|
||||
|
||||
dtype = columns[0][1].dtype
|
||||
for _, tensor in columns[1:]:
|
||||
dtype = torch.promote_types(dtype, tensor.dtype)
|
||||
tensors = [
|
||||
tensor if tensor.dtype == dtype else tensor.to(dtype) for _, tensor in columns
|
||||
]
|
||||
stacked = torch.stack(tensors, dim=1)
|
||||
return list(stacked.unbind(dim=0))
|
||||
|
||||
|
||||
def batch_to_tensor_columns(batch: pa.RecordBatch):
|
||||
"""
|
||||
Convert a PyArrow RecordBatch to a dict of per-column PyTorch Tensors.
|
||||
|
||||
Each tensor has shape ``(rows, *sample_shape)`` and shares Arrow storage
|
||||
where the layout allows it. Unlike ``torch_col`` and ``torch_row``, columns
|
||||
may have different sample shapes. This is the transform behind
|
||||
``Permutation.with_format("torch_dict")`` and can be consumed directly by
|
||||
a ``DataLoader`` with an identity ``collate_fn``.
|
||||
|
||||
Fails if torch is not installed.
|
||||
Fails if a column's data type is not supported by PyTorch.
|
||||
Fails if a column contains nulls.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
batch : pa.RecordBatch
|
||||
The record batch to convert.
|
||||
|
||||
Returns
|
||||
-------
|
||||
dict[str, torch.Tensor]
|
||||
A tensor per column, each with shape ``(rows, *sample_shape)``.
|
||||
"""
|
||||
_, columns = _batch_column_tensors(batch)
|
||||
return dict(columns)
|
||||
|
||||
|
||||
def batch_to_tensor_dict(batch: pa.RecordBatch):
|
||||
"""
|
||||
Convert a PyArrow RecordBatch to a list of per-row dicts of PyTorch Tensors.
|
||||
|
||||
Each column is first converted to a 1-D tensor (zero-copy via DLPack), then
|
||||
sliced per row. The result is a list whose length is ``batch.num_rows`` and
|
||||
whose items are dicts keyed by column name. This shape composes directly
|
||||
with PyTorch's default ``DataLoader`` collate, which stacks the per-row
|
||||
dicts back into a dict of batched tensors.
|
||||
Each column is converted to a tensor with shape ``(rows, *sample_shape)``,
|
||||
then sliced per row. The result is a list whose length is
|
||||
``batch.num_rows`` and whose items are dicts keyed by column name. This
|
||||
shape composes directly with PyTorch's default ``DataLoader`` collate,
|
||||
which stacks the per-row dicts back into a dict of batched tensors.
|
||||
|
||||
Fails if torch is not installed.
|
||||
Fails if a column's data type is not supported by PyTorch.
|
||||
Fails if a column contains nulls.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
@@ -665,14 +970,9 @@ def batch_to_tensor_dict(batch: pa.RecordBatch):
|
||||
-------
|
||||
list[dict[str, torch.Tensor]]
|
||||
One per-row dict per row in the batch. Each dict maps column name to a
|
||||
0-D tensor view into the column.
|
||||
tensor view into the column.
|
||||
"""
|
||||
torch = attempt_import_or_raise("torch", "torch")
|
||||
tensors = {
|
||||
name: torch.from_dlpack(col)
|
||||
for name, col in zip(batch.schema.names, batch.columns)
|
||||
}
|
||||
_, columns = _batch_column_tensors(batch)
|
||||
return [
|
||||
{name: tensor[i] for name, tensor in tensors.items()}
|
||||
for i in range(batch.num_rows)
|
||||
{name: tensor[i] for name, tensor in columns} for i in range(batch.num_rows)
|
||||
]
|
||||
|
||||
@@ -1017,6 +1017,11 @@ def test_take_queries_honor_blob_mode():
|
||||
1: b"one",
|
||||
2: b"two",
|
||||
}
|
||||
ordered = table.take_offsets([1, 0], preserve_order=True).to_arrow(
|
||||
blob_mode="bytes"
|
||||
)
|
||||
assert ordered["id"].to_pylist() == [2, 1]
|
||||
assert ordered["image"].to_pylist() == [b"two", b"one"]
|
||||
assert [
|
||||
row["image"] for row in table.take_row_ids([0]).to_list(blob_mode="bytes")
|
||||
] == [b"one"]
|
||||
@@ -1958,6 +1963,18 @@ def test_fetch_blob_apis_reject_missing_fragment_row_addr():
|
||||
_assert_fetch_apis_reject_missing_row_ids(table, [1 << 32, live])
|
||||
|
||||
|
||||
def test_fetch_blobs_missing_row_ids_suggest_take_offsets():
|
||||
table = _blob_table(
|
||||
"position_hint",
|
||||
[{"id": i, "image": b"x"} for i in range(3)],
|
||||
)
|
||||
with pytest.raises(ValueError, match="take_offsets") as exc:
|
||||
table.fetch_blobs("image", [10])
|
||||
message = str(exc.value)
|
||||
assert "first missing row ids: [10]" in message
|
||||
assert "with_row_id=True" in message
|
||||
|
||||
|
||||
def test_fetch_blob_apis_reject_deleted_row_ids():
|
||||
table = _blob_table(
|
||||
"deleted_rows",
|
||||
@@ -2216,8 +2233,11 @@ def test_fetch_blobs_from_query_result_without_row_id_raises():
|
||||
table = _blob_table("no_rowid", [{"id": 1, "image": b"x"}])
|
||||
hits = table.search().select(["id"]).to_arrow()
|
||||
assert "_rowid" not in hits.column_names
|
||||
with pytest.raises(ValueError, match="_rowid"):
|
||||
with pytest.raises(ValueError, match="take_offsets") as exc:
|
||||
table.fetch_blobs("image", hits)
|
||||
message = str(exc.value)
|
||||
assert "with_row_id=True" in message
|
||||
assert "list of row ids" in message
|
||||
|
||||
|
||||
_HYBRID_BLOB_SCHEMA = pa.schema(
|
||||
@@ -2384,6 +2404,77 @@ class _KeepAllScoresReranker(Reranker):
|
||||
return combined.append_column("_relevance_score", scores)
|
||||
|
||||
|
||||
class _RecordingVectorReranker(Reranker):
|
||||
def __init__(self):
|
||||
super().__init__(return_score="all")
|
||||
self.calls = []
|
||||
|
||||
def rerank_hybrid(self, query, vector_results, fts_results):
|
||||
raise AssertionError("vector queries must not call rerank_hybrid")
|
||||
|
||||
def rerank_vector(self, query, vector_results):
|
||||
self.calls.append((query, vector_results))
|
||||
return vector_results.append_column(
|
||||
"_relevance_score",
|
||||
pa.array([1.0] * len(vector_results), type=pa.float32()),
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("blob_mode", ["descriptions", "bytes"])
|
||||
def test_vector_to_arrow_reranks_before_blob_conversion(blob_mode, monkeypatch):
|
||||
db = lancedb.connect("memory:///")
|
||||
schema = pa.schema(
|
||||
[
|
||||
pa.field("id", pa.int64()),
|
||||
pa.field("vector", pa.list_(pa.float32(), list_size=2)),
|
||||
lancedb.blob("image"),
|
||||
]
|
||||
)
|
||||
table = db.create_table(f"vector_rerank_{blob_mode}", schema=schema)
|
||||
rows = 1100
|
||||
table.add(
|
||||
[
|
||||
{
|
||||
"id": row_id,
|
||||
"vector": [1.0, float(row_id % 2)],
|
||||
"image": f"image-{row_id}".encode(),
|
||||
}
|
||||
for row_id in range(rows)
|
||||
]
|
||||
)
|
||||
fetched = []
|
||||
fetch_blobs = table.fetch_blobs
|
||||
|
||||
def fetch(column, row_ids):
|
||||
fetched.append((column, len(row_ids)))
|
||||
return fetch_blobs(column, row_ids)
|
||||
|
||||
monkeypatch.setattr(table, "fetch_blobs", fetch)
|
||||
reranker = _RecordingVectorReranker()
|
||||
hits = (
|
||||
table.search([1.0, 0.0])
|
||||
.limit(rows)
|
||||
.select(["id", "image"])
|
||||
.rerank(reranker, "hello")
|
||||
.to_arrow(blob_mode=blob_mode)
|
||||
)
|
||||
|
||||
assert len(reranker.calls) == 1
|
||||
query, source = reranker.calls[0]
|
||||
assert query == "hello"
|
||||
# The reranker sees descriptors, not already-converted payload bytes.
|
||||
assert not pa.types.is_large_binary(source.schema.field("image").type)
|
||||
assert "_relevance_score" in hits.column_names
|
||||
assert len(hits) == rows
|
||||
if blob_mode == "bytes":
|
||||
# The whole lazy result is materialized before one aggregate conversion.
|
||||
assert fetched == [("image", rows)]
|
||||
assert pa.types.is_large_binary(hits.schema.field("image").type)
|
||||
else:
|
||||
assert fetched == []
|
||||
assert not pa.types.is_large_binary(hits.schema.field("image").type)
|
||||
|
||||
|
||||
def test_bytes_mode_rejects_legacy_blob_after_reranker_drops_metadata(tmp_path):
|
||||
db = lancedb.connect(tmp_path)
|
||||
table = db.create_table(
|
||||
@@ -3176,3 +3267,393 @@ async def test_open_blob_files_async_iterates_snapshot_handles(tmp_path):
|
||||
with file:
|
||||
actual.append(await file.aread())
|
||||
assert actual == [None, b"alpha", b"alpha"]
|
||||
|
||||
|
||||
def _initial_base_payloads(tmp_path):
|
||||
base_dir = tmp_path / "videos"
|
||||
base_dir.mkdir(exist_ok=True)
|
||||
payload = b"0123456789abcdef"
|
||||
clip = base_dir / "clip.mp4"
|
||||
clip.write_bytes(payload)
|
||||
return base_dir, clip, payload
|
||||
|
||||
|
||||
@pytest.mark.parametrize("base_spec", ["lightweight", "dict", "dataset_base_path"])
|
||||
@pytest.mark.parametrize("use_async", [False, True])
|
||||
@pytest.mark.asyncio
|
||||
async def test_create_table_initial_bases_store_relative_blob_ranges(
|
||||
tmp_path, base_spec, use_async
|
||||
):
|
||||
lance = None
|
||||
if base_spec == "dataset_base_path":
|
||||
lance = pytest.importorskip("lance")
|
||||
base_dir, clip, payload = _initial_base_payloads(tmp_path)
|
||||
field = lancedb.blob("video").with_metadata({"lancedb:logical_type": "mp4"})
|
||||
schema = pa.schema([pa.field("id", pa.int64()), field])
|
||||
videos = lancedb.blob_uri_array([clip.as_uri()], positions=[0], sizes=[6])
|
||||
batch = pa.RecordBatch.from_arrays(
|
||||
[pa.array([1], pa.int64()), videos], schema=schema
|
||||
)
|
||||
base_kwargs = {"path": base_dir.as_uri(), "name": "source", "id": 1}
|
||||
if base_spec == "lightweight":
|
||||
bases = [lancedb.BasePath(**base_kwargs)]
|
||||
elif base_spec == "dict":
|
||||
bases = [base_kwargs]
|
||||
else:
|
||||
bases = [lance.DatasetBasePath(**base_kwargs)]
|
||||
|
||||
if use_async:
|
||||
db = await lancedb.connect_async(tmp_path / "db")
|
||||
table = await db.create_table("videos", data=batch, initial_bases=bases)
|
||||
assert await table.version() == 1
|
||||
created_schema = await table.schema()
|
||||
reopened = await db.open_table("videos")
|
||||
hits = await reopened.query().with_row_id().to_arrow()
|
||||
row_id = hits["_rowid"][0].as_py()
|
||||
assert (await reopened.fetch_blobs("video", hits)).to_pylist() == [payload[:6]]
|
||||
assert (
|
||||
await reopened.fetch_blob_ranges("video", [(row_id, 1, 3)])
|
||||
).to_pylist() == [payload[1:4]]
|
||||
else:
|
||||
db = lancedb.connect(tmp_path / "db")
|
||||
table = db.create_table("videos", data=batch, initial_bases=bases)
|
||||
assert table.version == 1
|
||||
created_schema = table.schema
|
||||
# Manifest introspection needs pylance; the lightweight and dict
|
||||
# variants must still prove registration through the reopen and bytes.
|
||||
if lance is not None:
|
||||
registered = table.to_lance().base_paths()[1]
|
||||
assert registered.path == base_dir.as_uri()
|
||||
assert registered.is_dataset_root is False
|
||||
reopened = db.open_table("videos")
|
||||
hits = reopened.search().with_row_id(True).to_arrow()
|
||||
row_id = hits["_rowid"][0].as_py()
|
||||
assert reopened.fetch_blobs("video", hits).to_pylist() == [payload[:6]]
|
||||
assert reopened.fetch_blob_ranges("video", [(row_id, 1, 3)]).to_pylist() == [
|
||||
payload[1:4]
|
||||
]
|
||||
assert created_schema.field("video").metadata[b"lancedb:logical_type"] == b"mp4"
|
||||
|
||||
|
||||
def test_create_table_initial_bases_bootstrap_empty_table_with_auto_id(tmp_path):
|
||||
pytest.importorskip("lance")
|
||||
base_dir, clip, payload = _initial_base_payloads(tmp_path)
|
||||
schema = pa.schema([pa.field("id", pa.int64()), lancedb.blob("video")])
|
||||
db = lancedb.connect(tmp_path / "db")
|
||||
|
||||
table = db.create_table(
|
||||
"videos",
|
||||
schema=schema,
|
||||
initial_bases=[lancedb.BasePath(path=base_dir.as_uri(), name="source")],
|
||||
)
|
||||
assert table.version == 1
|
||||
registered = list(table.to_lance().base_paths().values())
|
||||
assert len(registered) == 1
|
||||
assert registered[0].id > 0
|
||||
assert registered[0].path == base_dir.as_uri()
|
||||
assert registered[0].is_dataset_root is False
|
||||
|
||||
videos = lancedb.blob_uri_array([clip.as_uri()])
|
||||
rows = pa.RecordBatch.from_arrays(
|
||||
[pa.array([1], pa.int64()), videos], schema=schema
|
||||
)
|
||||
table.add(rows)
|
||||
reopened = db.open_table("videos")
|
||||
by_id = _row_ids_by_id(reopened)
|
||||
assert reopened.fetch_blobs("video", [by_id[1]]).to_pylist() == [payload]
|
||||
|
||||
|
||||
def test_create_table_initial_bases_reject_bad_input(tmp_path):
|
||||
base_dir, _, _ = _initial_base_payloads(tmp_path)
|
||||
schema = pa.schema([pa.field("id", pa.int64()), lancedb.blob("video")])
|
||||
db = lancedb.connect("memory:///")
|
||||
path = base_dir.as_uri()
|
||||
|
||||
with pytest.raises(ValueError, match="id=0"):
|
||||
lancedb.BasePath(path=path, id=0)
|
||||
with pytest.raises(ValueError, match="id=0"):
|
||||
db.create_table("zero", schema=schema, initial_bases=[{"path": path, "id": 0}])
|
||||
with pytest.raises(ValueError, match="unique"):
|
||||
db.create_table(
|
||||
"duplicates",
|
||||
schema=schema,
|
||||
initial_bases=[
|
||||
lancedb.BasePath(path=path, id=1),
|
||||
lancedb.BasePath(path=f"{path}/other", id=1),
|
||||
],
|
||||
)
|
||||
with pytest.raises(ValueError, match="missing 'path'"):
|
||||
db.create_table("missing_path", schema=schema, initial_bases=[{"id": 1}])
|
||||
with pytest.raises(TypeError, match="must be a BasePath, dict, or DatasetBasePath"):
|
||||
db.create_table("not_a_base", schema=schema, initial_bases=[object()])
|
||||
|
||||
|
||||
def test_create_table_allow_external_blob_outside_bases_is_atomic(tmp_path):
|
||||
payload = b"0123456789abcdef"
|
||||
clip = tmp_path / "clip.mp4"
|
||||
clip.write_bytes(payload)
|
||||
schema = pa.schema([pa.field("id", pa.int64()), lancedb.blob("video")])
|
||||
videos = lancedb.blob_uri_array([clip.as_uri()], positions=[0], sizes=[6])
|
||||
rows = pa.RecordBatch.from_arrays(
|
||||
[pa.array([1], pa.int64()), videos], schema=schema
|
||||
)
|
||||
db = lancedb.connect(tmp_path / "db")
|
||||
|
||||
with pytest.raises(ValueError, match="allow_external_blob_outside_bases"):
|
||||
db.create_table("rejected", data=rows, schema=schema)
|
||||
with pytest.raises(ValueError, match="requires initial data"):
|
||||
db.create_table(
|
||||
"empty_opt_in", schema=schema, allow_external_blob_outside_bases=True
|
||||
)
|
||||
|
||||
table = db.create_table(
|
||||
"videos", data=rows, schema=schema, allow_external_blob_outside_bases=True
|
||||
)
|
||||
assert table.version == 1
|
||||
reopened = db.open_table("videos")
|
||||
hits = reopened.search().with_row_id(True).to_arrow()
|
||||
assert reopened.fetch_blobs("video", hits).to_pylist() == [payload[:6]]
|
||||
row_id = hits["_rowid"][0].as_py()
|
||||
assert reopened.fetch_blob_ranges("video", [(row_id, 0, 6)]).to_pylist() == [
|
||||
payload[:6]
|
||||
]
|
||||
|
||||
|
||||
def test_create_table_initial_bases_keep_scoped_options_on_reopen(tmp_path):
|
||||
pytest.importorskip("lance")
|
||||
payload = b"scoped-payload"
|
||||
dir_a = tmp_path / "base-a"
|
||||
dir_b = tmp_path / "base-b"
|
||||
dir_a.mkdir()
|
||||
dir_b.mkdir()
|
||||
clip_a = dir_a / "clip.mp4"
|
||||
clip_b = dir_b / "clip.mp4"
|
||||
clip_a.write_bytes(payload)
|
||||
clip_b.write_bytes(payload)
|
||||
schema = pa.schema([pa.field("id", pa.int64()), lancedb.blob("video")])
|
||||
videos = lancedb.blob_uri_array([clip_a.as_uri(), clip_b.as_uri()])
|
||||
rows = pa.RecordBatch.from_arrays(
|
||||
[pa.array([1, 2], pa.int64()), videos], schema=schema
|
||||
)
|
||||
storage_options = {
|
||||
"timeout": "7s",
|
||||
"base_1.region": "base-one",
|
||||
"base_2.region": "base-two",
|
||||
}
|
||||
db = lancedb.connect(tmp_path / "db")
|
||||
|
||||
table = db.create_table(
|
||||
"videos",
|
||||
data=rows,
|
||||
schema=schema,
|
||||
initial_bases=[
|
||||
lancedb.BasePath(path=dir_a.as_uri(), name="a", id=1),
|
||||
lancedb.BasePath(path=dir_b.as_uri(), name="b", id=2),
|
||||
],
|
||||
storage_options=storage_options,
|
||||
)
|
||||
assert table.version == 1
|
||||
assert {base.id for base in table.to_lance().base_paths().values()} == {1, 2}
|
||||
|
||||
reopened = db.open_table("videos", storage_options=storage_options)
|
||||
by_id = _row_ids_by_id(reopened)
|
||||
assert reopened.fetch_blobs("video", [by_id[1], by_id[2]]).to_pylist() == [
|
||||
payload,
|
||||
payload,
|
||||
]
|
||||
|
||||
|
||||
def test_create_table_initial_bases_through_namespace(tmp_path):
|
||||
pytest.importorskip("lance")
|
||||
base_dir, clip, payload = _initial_base_payloads(tmp_path)
|
||||
schema = pa.schema([pa.field("id", pa.int64()), lancedb.blob("video")])
|
||||
videos = lancedb.blob_uri_array([clip.as_uri()], positions=[0], sizes=[6])
|
||||
rows = pa.RecordBatch.from_arrays(
|
||||
[pa.array([1], pa.int64()), videos], schema=schema
|
||||
)
|
||||
db = lancedb.connect_namespace("dir", {"root": str(tmp_path / "ns")})
|
||||
|
||||
table = db.create_table(
|
||||
"videos",
|
||||
data=rows,
|
||||
schema=schema,
|
||||
initial_bases=[lancedb.BasePath(path=base_dir.as_uri(), name="source", id=1)],
|
||||
)
|
||||
assert table.version == 1
|
||||
reopened = db.open_table("videos")
|
||||
hits = reopened.search().with_row_id(True).to_arrow()
|
||||
row_id = hits["_rowid"][0].as_py()
|
||||
assert reopened.fetch_blobs("video", hits).to_pylist() == [payload[:6]]
|
||||
assert reopened.fetch_blob_ranges("video", [(row_id, 1, 3)]).to_pylist() == [
|
||||
payload[1:4]
|
||||
]
|
||||
|
||||
|
||||
def test_namespace_create_keeps_scoped_options_over_connection_defaults(tmp_path):
|
||||
pytest.importorskip("lance")
|
||||
base_dir, clip, _ = _initial_base_payloads(tmp_path)
|
||||
schema = pa.schema([pa.field("id", pa.int64()), lancedb.blob("video")])
|
||||
videos = lancedb.blob_uri_array([clip.as_uri()])
|
||||
rows = pa.RecordBatch.from_arrays(
|
||||
[pa.array([1], pa.int64()), videos], schema=schema
|
||||
)
|
||||
db = lancedb.connect_namespace(
|
||||
"dir",
|
||||
{"root": str(tmp_path / "ns")},
|
||||
storage_options={"timeout": "7s"},
|
||||
)
|
||||
|
||||
# The invalid scoped option belongs to base 1. It must survive the merge
|
||||
# with connection defaults instead of being replaced by them.
|
||||
with pytest.raises(ValueError, match="scheduler_error_mode"):
|
||||
db.create_table(
|
||||
"videos",
|
||||
data=rows,
|
||||
schema=schema,
|
||||
initial_bases=[
|
||||
lancedb.BasePath(path=base_dir.as_uri(), name="source", id=1)
|
||||
],
|
||||
storage_options={"base_1.scheduler_error_mode": "invalid"},
|
||||
)
|
||||
|
||||
|
||||
def test_namespace_reopen_applies_scoped_options_per_base(tmp_path):
|
||||
pytest.importorskip("lance")
|
||||
payload_a = b"namespace-base-a"
|
||||
payload_b = b"namespace-base-b"
|
||||
dir_a = tmp_path / "base-a"
|
||||
dir_b = tmp_path / "base-b"
|
||||
dir_a.mkdir()
|
||||
dir_b.mkdir()
|
||||
clip_a = dir_a / "clip.mp4"
|
||||
clip_b = dir_b / "clip.mp4"
|
||||
clip_a.write_bytes(payload_a)
|
||||
clip_b.write_bytes(payload_b)
|
||||
schema = pa.schema([pa.field("id", pa.int64()), lancedb.blob("video")])
|
||||
videos = lancedb.blob_uri_array([clip_a.as_uri(), clip_b.as_uri()])
|
||||
rows = pa.RecordBatch.from_arrays(
|
||||
[pa.array([1, 2], pa.int64()), videos], schema=schema
|
||||
)
|
||||
db = lancedb.connect_namespace(
|
||||
"dir",
|
||||
{"root": str(tmp_path / "ns")},
|
||||
storage_options={"timeout": "7s"},
|
||||
)
|
||||
|
||||
table = db.create_table(
|
||||
"videos",
|
||||
data=rows,
|
||||
schema=schema,
|
||||
initial_bases=[
|
||||
lancedb.BasePath(path=dir_a.as_uri(), name="a", id=1),
|
||||
lancedb.BasePath(path=dir_b.as_uri(), name="b", id=2),
|
||||
],
|
||||
)
|
||||
assert table.version == 1
|
||||
|
||||
reopened = db.open_table(
|
||||
"videos", storage_options={"base_1.scheduler_error_mode": "invalid"}
|
||||
)
|
||||
by_id = _row_ids_by_id(reopened)
|
||||
with pytest.raises(ValueError, match="scheduler_error_mode"):
|
||||
reopened.fetch_blobs("video", [by_id[1]])
|
||||
assert reopened.fetch_blobs("video", [by_id[2]]).to_pylist() == [payload_b]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_create_table_initial_bases_through_async_namespace(tmp_path):
|
||||
pytest.importorskip("lance")
|
||||
base_dir, clip, payload = _initial_base_payloads(tmp_path)
|
||||
schema = pa.schema([pa.field("id", pa.int64()), lancedb.blob("video")])
|
||||
videos = lancedb.blob_uri_array([clip.as_uri()])
|
||||
rows = pa.RecordBatch.from_arrays(
|
||||
[pa.array([1], pa.int64()), videos], schema=schema
|
||||
)
|
||||
db = lancedb.connect_namespace_async("dir", {"root": str(tmp_path / "ns")})
|
||||
|
||||
table = await db.create_table(
|
||||
"videos",
|
||||
data=rows,
|
||||
schema=schema,
|
||||
initial_bases=[lancedb.BasePath(path=base_dir.as_uri(), name="source", id=1)],
|
||||
)
|
||||
assert await table.version() == 1
|
||||
reopened = await db.open_table("videos")
|
||||
hits = await reopened.query().with_row_id().to_arrow()
|
||||
assert (await reopened.fetch_blobs("video", hits)).to_pylist() == [payload]
|
||||
|
||||
|
||||
def test_namespace_refresh_layers_caller_scoped_options(tmp_path):
|
||||
from lance_namespace import (
|
||||
DeclareTableResponse,
|
||||
DescribeTableResponse,
|
||||
LanceNamespace,
|
||||
)
|
||||
from lancedb.namespace import LanceNamespaceDBConnection
|
||||
|
||||
class RefreshingNamespace(LanceNamespace):
|
||||
def __init__(self, location):
|
||||
self.location = location
|
||||
self.refreshes = 0
|
||||
|
||||
def namespace_id(self):
|
||||
return self.location
|
||||
|
||||
def declare_table(self, request):
|
||||
return DeclareTableResponse(
|
||||
location=self.location,
|
||||
storage_options={
|
||||
"timeout": "7s",
|
||||
# Expired immediately so the next read must refresh.
|
||||
"expires_at_millis": "1",
|
||||
},
|
||||
)
|
||||
|
||||
def describe_table(self, request):
|
||||
self.refreshes += 1
|
||||
return DescribeTableResponse(
|
||||
location=self.location,
|
||||
storage_options={"timeout": "8s", "namespace_vended": "fresh"},
|
||||
)
|
||||
|
||||
payload = b"0123456789abcdef"
|
||||
base_dir = tmp_path / "base"
|
||||
base_dir.mkdir()
|
||||
clip = base_dir / "clip.mp4"
|
||||
clip.write_bytes(payload)
|
||||
schema = pa.schema([pa.field("id", pa.int64()), lancedb.blob("video")])
|
||||
videos = lancedb.blob_uri_array([clip.as_uri()])
|
||||
rows = pa.RecordBatch.from_arrays(
|
||||
[pa.array([1], pa.int64()), videos], schema=schema
|
||||
)
|
||||
namespace = RefreshingNamespace((tmp_path / "table.lance").as_uri())
|
||||
db = LanceNamespaceDBConnection(namespace)
|
||||
|
||||
table = db.create_table(
|
||||
"videos",
|
||||
data=rows,
|
||||
schema=schema,
|
||||
initial_bases=[lancedb.BasePath(base_dir.as_uri(), name="base", id=1)],
|
||||
storage_options={"base_1.caller_scoped": "keep-me"},
|
||||
)
|
||||
initial = table.initial_storage_options()
|
||||
assert initial["base_1.caller_scoped"] == "keep-me"
|
||||
assert initial["timeout"] == "7s"
|
||||
|
||||
latest = table.latest_storage_options()
|
||||
assert namespace.refreshes > 0, "expired seed did not trigger a refresh"
|
||||
assert latest["base_1.caller_scoped"] == "keep-me"
|
||||
assert latest["timeout"] == "8s"
|
||||
assert latest["namespace_vended"] == "fresh"
|
||||
assert table.version == 1
|
||||
|
||||
reopened = db.open_table(
|
||||
"videos", storage_options={"base_1.caller_scoped": "keep-me"}
|
||||
)
|
||||
assert reopened.latest_storage_options()["base_1.caller_scoped"] == "keep-me"
|
||||
hits = reopened.search().with_row_id(True).to_arrow()
|
||||
row_id = hits["_rowid"][0].as_py()
|
||||
assert reopened.fetch_blobs("video", [row_id]).to_pylist() == [payload]
|
||||
assert reopened.fetch_blob_ranges("video", [(row_id, 4, 6)]).to_pylist() == [
|
||||
payload[4:10]
|
||||
]
|
||||
|
||||
@@ -85,3 +85,133 @@ def test_blob_array(with_pylance):
|
||||
text=True,
|
||||
)
|
||||
assert result.returncode == 0, result.stderr
|
||||
|
||||
|
||||
@pytest.mark.parametrize("with_pylance", [False, True])
|
||||
def test_blob_uri_array(with_pylance):
|
||||
if with_pylance:
|
||||
pytest.importorskip("lance")
|
||||
# Use fresh processes so each extension class can own Arrow's registry.
|
||||
script = textwrap.dedent(
|
||||
"""\
|
||||
import importlib.abc
|
||||
import pathlib
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
if sys.argv[1] == "False":
|
||||
class MissingLance(importlib.abc.MetaPathFinder):
|
||||
def find_spec(self, fullname, path, target=None):
|
||||
if fullname == "lance" or fullname.startswith("lance."):
|
||||
raise ModuleNotFoundError(fullname, name="lance")
|
||||
sys.meta_path.insert(0, MissingLance())
|
||||
|
||||
import lancedb
|
||||
import pyarrow as pa
|
||||
from lancedb import BasePath, blob_uri_array
|
||||
from lancedb.schema import blob
|
||||
|
||||
if sys.argv[1] == "True":
|
||||
from lance import DatasetBasePath
|
||||
from lance.blob import BlobType
|
||||
else:
|
||||
from lancedb.schema import _FallbackBlobType as BlobType
|
||||
DatasetBasePath = None
|
||||
|
||||
schema = pa.schema([blob("video")])
|
||||
array = blob_uri_array(
|
||||
["s3://bucket/a.mp4", None, "b.mp4"],
|
||||
positions=[0, None, None],
|
||||
sizes=[4, None, None],
|
||||
)
|
||||
assert isinstance(array, pa.ExtensionArray)
|
||||
assert type(array.type) is BlobType
|
||||
assert array.type == schema.field("video").type
|
||||
assert array.storage.to_pylist() == [
|
||||
{"data": None, "uri": "s3://bucket/a.mp4", "position": 0, "size": 4},
|
||||
None,
|
||||
{"data": None, "uri": "b.mp4", "position": None, "size": None},
|
||||
]
|
||||
whole = blob_uri_array(iter(["s3://bucket/a.mp4"]))
|
||||
assert whole.storage.to_pylist() == [
|
||||
{"data": None, "uri": "s3://bucket/a.mp4", "position": None, "size": None}
|
||||
]
|
||||
|
||||
checks = [
|
||||
(lambda: blob_uri_array(["u"], positions=[0]), "provided together"),
|
||||
(
|
||||
lambda: blob_uri_array(["u"], positions=[0, 0], sizes=[1, 1]),
|
||||
"same length",
|
||||
),
|
||||
(
|
||||
lambda: blob_uri_array(["u"], sizes=[1, 1], positions=[0, 0]),
|
||||
"same length",
|
||||
),
|
||||
(
|
||||
lambda: blob_uri_array(["u"], positions=[0], sizes=[None]),
|
||||
"both position and size",
|
||||
),
|
||||
(lambda: blob_uri_array(["u"], positions=[0], sizes=[0]), "positive"),
|
||||
(lambda: blob_uri_array(["u"], positions=[-1], sizes=[1]), "non-negative"),
|
||||
(lambda: blob_uri_array([None], positions=[0], sizes=[1]), "None but"),
|
||||
(lambda: blob_uri_array(["u"], positions=[0], sizes=[2**64]), "uint64"),
|
||||
(lambda: blob_uri_array([b"u"]), "must be a string"),
|
||||
]
|
||||
for call, fragment in checks:
|
||||
try:
|
||||
call()
|
||||
except (TypeError, ValueError, OverflowError) as error:
|
||||
assert fragment in str(error), (fragment, error)
|
||||
else:
|
||||
raise AssertionError(f"accepted invalid input: {fragment}")
|
||||
|
||||
try:
|
||||
BasePath("s3://bucket", id=0)
|
||||
except ValueError as error:
|
||||
assert "id=None" in str(error)
|
||||
else:
|
||||
raise AssertionError("accepted explicit id=0")
|
||||
|
||||
# The public create route must accept the helper and register the base
|
||||
# in the same commit as the data, with or without pylance.
|
||||
root = pathlib.Path(tempfile.mkdtemp())
|
||||
base_dir = root / "videos"
|
||||
base_dir.mkdir()
|
||||
payload = b"0123456789abcdef"
|
||||
clip = base_dir / "clip.mp4"
|
||||
clip.write_bytes(payload)
|
||||
db = lancedb.connect(root / "db")
|
||||
field = blob("video").with_metadata({"lancedb:logical_type": "mp4"})
|
||||
table_schema = pa.schema([pa.field("id", pa.int64()), field])
|
||||
videos = blob_uri_array([clip.as_uri()], positions=[0], sizes=[6])
|
||||
batch = pa.RecordBatch.from_arrays(
|
||||
[pa.array([1], pa.int64()), videos], schema=table_schema
|
||||
)
|
||||
if DatasetBasePath is not None:
|
||||
bases = [DatasetBasePath(path=base_dir.as_uri(), name="source")]
|
||||
else:
|
||||
bases = [BasePath(path=base_dir.as_uri(), name="source")]
|
||||
table = db.create_table("videos", data=batch, initial_bases=bases)
|
||||
assert table.version == 1
|
||||
assert (
|
||||
table.schema.field("video").metadata[b"lancedb:logical_type"] == b"mp4"
|
||||
)
|
||||
row_ids = table.search().with_row_id(True).to_arrow()["_rowid"]
|
||||
assert table.fetch_blobs("video", row_ids).to_pylist() == [payload[:6]]
|
||||
assert table.fetch_blob_ranges(
|
||||
"video", [(row_ids[0].as_py(), 1, 3)]
|
||||
).to_pylist() == [payload[1:4]]
|
||||
if DatasetBasePath is not None:
|
||||
base_paths = table.to_lance().base_paths()
|
||||
assert base_paths[1].path == base_dir.as_uri()
|
||||
assert base_paths[1].is_dataset_root is False
|
||||
if sys.argv[1] == "False":
|
||||
assert "lance" not in sys.modules
|
||||
"""
|
||||
)
|
||||
result = subprocess.run(
|
||||
[sys.executable, "-c", script, str(with_pylance)],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
)
|
||||
assert result.returncode == 0, result.stderr
|
||||
|
||||
@@ -869,6 +869,35 @@ def test_open_table_sync(tmp_db: lancedb.DBConnection):
|
||||
tmp_db.open_table("does_not_exist")
|
||||
|
||||
|
||||
def test_open_table_sync_with_location(tmp_path):
|
||||
db = lancedb.connect(tmp_path / "db")
|
||||
db.create_table("test", data=[{"id": 0}])
|
||||
dataset_path = tmp_path / "db" / "test.lance"
|
||||
|
||||
other_db = lancedb.connect(tmp_path / "other")
|
||||
opened = other_db.open_table("test", location=str(dataset_path))
|
||||
assert opened.name == "test"
|
||||
assert opened.count_rows() == 1
|
||||
|
||||
|
||||
def test_open_table_sync_lance_dataset_path_hint(tmp_path):
|
||||
data_dir = tmp_path / "data"
|
||||
lancedb.connect(data_dir).create_table("embeddings", data=[{"id": 0}])
|
||||
dataset_db = lancedb.connect(data_dir / "embeddings.lance")
|
||||
|
||||
with pytest.raises(ValueError) as exc_info:
|
||||
dataset_db.open_table("embeddings")
|
||||
message = str(exc_info.value)
|
||||
assert "Table 'embeddings' was not found" in message
|
||||
assert "points to a Lance dataset rather than a database directory" in message
|
||||
assert f"parent directory '{data_dir}'" in message
|
||||
assert "open table 'embeddings' instead" in message
|
||||
|
||||
with pytest.raises(ValueError) as exc_info:
|
||||
dataset_db.open_table("missing", location=str(tmp_path / "missing.lance"))
|
||||
assert "points to a Lance dataset" not in str(exc_info.value)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_open_table(tmp_path):
|
||||
from conftest import pandas_string_type
|
||||
|
||||
@@ -1224,6 +1224,31 @@ def test_transform_fn_pandas(mem_db):
|
||||
assert isinstance(result, pd.DataFrame)
|
||||
|
||||
|
||||
def test_numpy_format_mixed_columns_is_object_ndarray(mem_db):
|
||||
pytest.importorskip("pandas")
|
||||
import numpy as np
|
||||
|
||||
tbl = mem_db.create_table(
|
||||
"test_table",
|
||||
pa.table(
|
||||
{
|
||||
"id": range(3),
|
||||
"vector": pa.array(
|
||||
[[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]],
|
||||
type=pa.list_(pa.float32(), 2),
|
||||
),
|
||||
}
|
||||
),
|
||||
)
|
||||
permutation = Permutation.identity(tbl).with_format("numpy")
|
||||
result = next(permutation.iter(2, skip_last_batch=False))
|
||||
|
||||
assert isinstance(result, np.ndarray)
|
||||
assert result.dtype == object
|
||||
assert result.shape == (2, 2)
|
||||
np.testing.assert_array_equal(result[0, 1], [1.0, 2.0])
|
||||
|
||||
|
||||
def test_custom_transform(mem_db):
|
||||
tbl = mem_db.create_table(
|
||||
"test_table", pa.table({"id": range(10), "value": range(10)})
|
||||
|
||||
@@ -975,6 +975,10 @@ async def test_async_take_query_to_pandas_blob_v2_bytes(tmp_db_async):
|
||||
|
||||
df = await table.take_offsets([1, 2]).to_pandas(blob_mode="bytes")
|
||||
assert set(df["blob"]) == {b"two", b"three"}
|
||||
ordered = await table.take_offsets([2, 1], preserve_order=True).to_pandas(
|
||||
blob_mode="bytes"
|
||||
)
|
||||
assert ordered["blob"].tolist() == [b"three", b"two"]
|
||||
|
||||
|
||||
def test_order_by_plain_query(mem_db):
|
||||
@@ -1739,17 +1743,16 @@ def test_query_builder_with_different_vector_column():
|
||||
ds = mock.Mock()
|
||||
table.to_lance.return_value = ds
|
||||
builder.to_arrow()
|
||||
table._execute_arrow.assert_called_once_with(
|
||||
Query(
|
||||
vector=query,
|
||||
filter="b < 10",
|
||||
limit=2,
|
||||
distance_type="cosine",
|
||||
columns=["b"],
|
||||
vector_column="foo_vector",
|
||||
),
|
||||
timeout=None,
|
||||
expected = Query(
|
||||
vector=query,
|
||||
filter="b < 10",
|
||||
limit=2,
|
||||
distance_type="cosine",
|
||||
columns=["b"],
|
||||
vector_column="foo_vector",
|
||||
)
|
||||
expected._blob_row_id_prepared = True
|
||||
table._execute_arrow.assert_called_once_with(expected, timeout=None)
|
||||
|
||||
|
||||
def cosine_distance(vec1, vec2):
|
||||
@@ -2657,6 +2660,61 @@ def test_query_schema(tmp_path):
|
||||
)
|
||||
|
||||
|
||||
def test_sync_query_prepares_schema_once_per_execution(tmp_path, monkeypatch):
|
||||
db = lancedb.connect(tmp_path)
|
||||
table = db.create_table(
|
||||
"test",
|
||||
pa.table(
|
||||
{
|
||||
"id": [1, 2, 3],
|
||||
"vector": pa.array(
|
||||
[[1, 2], [3, 4], [5, 6]],
|
||||
pa.list_(pa.float32(), list_size=2),
|
||||
),
|
||||
}
|
||||
),
|
||||
)
|
||||
|
||||
calls = 0
|
||||
original = AsyncTable._schema_sync
|
||||
|
||||
def counted(self):
|
||||
nonlocal calls
|
||||
calls += 1
|
||||
return original(self)
|
||||
|
||||
monkeypatch.setattr(AsyncTable, "_schema_sync", counted)
|
||||
|
||||
table.search().where("id = 1").select(["id"]).to_arrow()
|
||||
assert calls <= 1
|
||||
|
||||
calls = 0
|
||||
table.search([1, 2], vector_column_name="vector").limit(1).to_arrow()
|
||||
assert calls <= 1
|
||||
|
||||
calls = 0
|
||||
table.search([1, 2]).limit(1).to_arrow()
|
||||
# At most one lookup infers the vector column, one prepares execution.
|
||||
assert calls <= 2
|
||||
|
||||
calls = 0
|
||||
table.search().where("id = 1").select(["id"]).to_batches().read_all()
|
||||
assert calls <= 1
|
||||
|
||||
builder = table.search().where("id = 1")
|
||||
before = builder.to_arrow()
|
||||
assert "extra" not in before.column_names
|
||||
assert "image" not in before.column_names
|
||||
|
||||
table.add_columns(pa.schema([pa.field("extra", pa.int64()), lancedb.blob("image")]))
|
||||
calls = 0
|
||||
after = builder.to_arrow()
|
||||
assert calls <= 1
|
||||
assert after["extra"].to_pylist() == [None]
|
||||
assert "_lance_row_id" in str(after.schema)
|
||||
assert "_rowid" not in after.column_names
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_query_schema_async(tmp_path):
|
||||
db = await lancedb.connect_async(tmp_path)
|
||||
@@ -2761,6 +2819,86 @@ def test_take_queries(tmp_path):
|
||||
assert table.take_row_ids([5, 2, 17]).to_pandas()["idx"].to_list() == [5, 2, 17]
|
||||
|
||||
|
||||
def test_take_offsets_preserve_order_sync(tmp_path):
|
||||
db = lancedb.connect(tmp_path)
|
||||
table = db.create_table("test", pa.table({"idx": range(4)}))
|
||||
table.add(pa.table({"idx": range(4, 8)}))
|
||||
table.delete("idx IN (1, 6)")
|
||||
requested = [5, 0, 5, 2, 99, 4, 0]
|
||||
expected = [7, 0, 7, 3, 5, 0]
|
||||
|
||||
actual = (
|
||||
table.take_offsets(requested, preserve_order=True).select(["idx"]).to_arrow()
|
||||
)
|
||||
assert actual.column_names == ["idx"]
|
||||
assert actual["idx"].to_pylist() == expected
|
||||
|
||||
batches = list(
|
||||
table.take_offsets(requested, preserve_order=True)
|
||||
.select(["idx"])
|
||||
.to_batches(max_batch_length=1)
|
||||
)
|
||||
assert all(batch.num_rows <= 1 for batch in batches)
|
||||
assert [row for batch in batches for row in batch["idx"].to_pylist()] == expected
|
||||
|
||||
# The default path keeps its unspecified-order behavior.
|
||||
default = table.take_offsets(requested).select(["idx"]).to_arrow()
|
||||
assert sorted(default["idx"].to_pylist()) == sorted(expected)
|
||||
|
||||
assert table.take_offsets(requested).to_query_object().preserve_order is None
|
||||
query = (
|
||||
table.take_offsets(requested, preserve_order=True)
|
||||
.select(["idx"])
|
||||
.to_query_object()
|
||||
)
|
||||
assert query.preserve_order is True
|
||||
assert table._execute_query(query).read_all()["idx"].to_pylist() == expected
|
||||
|
||||
empty = table.take_offsets([], preserve_order=True).select(["idx"]).to_arrow()
|
||||
assert empty.num_rows == 0
|
||||
assert empty.column_names == ["idx"]
|
||||
|
||||
query.order_by = [ColumnOrdering(column_name="idx")]
|
||||
with pytest.raises(
|
||||
ValueError, match="preserve_order cannot be combined with an explicit order_by"
|
||||
):
|
||||
table._execute_query(query)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_take_offsets_preserve_order_async(tmp_path):
|
||||
db = await lancedb.connect_async(tmp_path)
|
||||
table = await db.create_table("test", pa.table({"idx": range(4)}))
|
||||
await table.add(pa.table({"idx": range(4, 8)}))
|
||||
await table.delete("idx IN (1, 6)")
|
||||
requested = [5, 0, 5, 2, 99, 4, 0]
|
||||
expected = [7, 0, 7, 3, 5, 0]
|
||||
|
||||
actual = (
|
||||
await table.take_offsets(requested, preserve_order=True)
|
||||
.select(["idx"])
|
||||
.to_arrow()
|
||||
)
|
||||
assert actual.column_names == ["idx"]
|
||||
assert actual["idx"].to_pylist() == expected
|
||||
|
||||
reader = (
|
||||
await table.take_offsets(requested, preserve_order=True)
|
||||
.select(["idx"])
|
||||
.to_batches(max_batch_length=1)
|
||||
)
|
||||
batches = [batch async for batch in reader]
|
||||
assert all(batch.num_rows <= 1 for batch in batches)
|
||||
assert [row for batch in batches for row in batch["idx"].to_pylist()] == expected
|
||||
|
||||
query = (
|
||||
table.take_offsets(requested, preserve_order=True)
|
||||
.select(["idx"])
|
||||
.to_query_object()
|
||||
)
|
||||
assert query.preserve_order is True
|
||||
|
||||
|
||||
@pytest.mark.parametrize("selection", [None, [], ["idx"], {"_rowid": "100 - idx"}])
|
||||
@pytest.mark.parametrize("empty", [False, True])
|
||||
def test_take_row_ids_order_and_roundtrip(tmp_path, selection, empty):
|
||||
@@ -2867,6 +3005,13 @@ def test_getitems(tmp_path):
|
||||
assert table.__getitems__(offsets) == pa.table({"idx": offsets})
|
||||
|
||||
|
||||
def test_getitems_rejects_missing_offsets(tmp_path):
|
||||
table = lancedb.connect(tmp_path).create_table("test", pa.table({"idx": range(3)}))
|
||||
|
||||
with pytest.raises(pa.ArrowIndexError, match="out of bounds"):
|
||||
table.__getitems__([0, 99])
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_query_timeout_async(tmp_path):
|
||||
db = await lancedb.connect_async(tmp_path)
|
||||
|
||||
@@ -1404,6 +1404,12 @@ def test_remote_permutation_is_picklable():
|
||||
{"a": 2},
|
||||
{"a": 4},
|
||||
]
|
||||
assert table.take_offsets([0, 2, 0, 4], preserve_order=True).to_list() == [
|
||||
{"a": 0},
|
||||
{"a": 2},
|
||||
{"a": 0},
|
||||
{"a": 4},
|
||||
]
|
||||
|
||||
permutation = Permutation.identity(table)
|
||||
restored = pickle.loads(pickle.dumps(permutation))
|
||||
@@ -1530,6 +1536,126 @@ def test_create_table_positional_parameters_match_base_contract():
|
||||
assert actual == expected
|
||||
|
||||
|
||||
def _unconsumed_create_input():
|
||||
raise AssertionError("create_table consumed input before rejecting the option")
|
||||
yield # pragma: no cover
|
||||
|
||||
|
||||
def _assert_enterprise_rejection(error):
|
||||
message = str(error)
|
||||
assert "not supported for table creation in LanceDB Enterprise" in message
|
||||
assert "Embedded" not in message
|
||||
assert "add(" not in message
|
||||
|
||||
|
||||
def test_create_table_rejects_blob_base_options_before_request():
|
||||
def handler(request):
|
||||
raise AssertionError(f"unexpected request: {request.path}")
|
||||
|
||||
schema = pa.schema([pa.field("id", pa.int64())])
|
||||
with mock_lancedb_connection(handler) as db:
|
||||
with pytest.raises(NotImplementedError, match="initial_bases") as error:
|
||||
db.create_table(
|
||||
"test",
|
||||
data=_unconsumed_create_input(),
|
||||
initial_bases=[{"path": "s3://bucket/prefix"}],
|
||||
)
|
||||
_assert_enterprise_rejection(error.value)
|
||||
with pytest.raises(
|
||||
NotImplementedError, match="allow_external_blob_outside_bases"
|
||||
) as error:
|
||||
db.create_table(
|
||||
"test",
|
||||
data=_unconsumed_create_input(),
|
||||
allow_external_blob_outside_bases=True,
|
||||
)
|
||||
_assert_enterprise_rejection(error.value)
|
||||
with pytest.raises(
|
||||
NotImplementedError, match="allow_external_blob_outside_bases"
|
||||
) as error:
|
||||
db.create_table(
|
||||
"test",
|
||||
schema=schema,
|
||||
allow_external_blob_outside_bases=True,
|
||||
)
|
||||
_assert_enterprise_rejection(error.value)
|
||||
|
||||
|
||||
def test_create_table_accepts_empty_blob_base_options():
|
||||
def handler(request):
|
||||
assert request.path == "/v1/table/test/create/?mode=create"
|
||||
request.send_response(200)
|
||||
request.send_header("Content-Type", "application/json")
|
||||
request.end_headers()
|
||||
request.wfile.write(b"{}")
|
||||
|
||||
schema = pa.schema([pa.field("id", pa.int64())])
|
||||
with mock_lancedb_connection(handler) as db:
|
||||
table = db.create_table(
|
||||
"test",
|
||||
schema=schema,
|
||||
initial_bases=[],
|
||||
allow_external_blob_outside_bases=False,
|
||||
)
|
||||
assert table is not None
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_create_table_rejects_blob_base_options_before_request_async():
|
||||
def handler(request):
|
||||
raise AssertionError(f"unexpected request: {request.path}")
|
||||
|
||||
def reader():
|
||||
schema = pa.schema([pa.field("id", pa.int64())])
|
||||
return pa.RecordBatchReader.from_batches(schema, [])
|
||||
|
||||
schema = pa.schema([pa.field("id", pa.int64())])
|
||||
async with mock_lancedb_connection_async(handler) as db:
|
||||
with pytest.raises(NotImplementedError, match="initial_bases") as error:
|
||||
await db.create_table(
|
||||
"test",
|
||||
data=_unconsumed_create_input(),
|
||||
initial_bases=[{"path": "s3://bucket/prefix"}],
|
||||
)
|
||||
_assert_enterprise_rejection(error.value)
|
||||
with pytest.raises(
|
||||
NotImplementedError, match="allow_external_blob_outside_bases"
|
||||
) as error:
|
||||
await db.create_table(
|
||||
"test",
|
||||
data=_unconsumed_create_input(),
|
||||
allow_external_blob_outside_bases=True,
|
||||
)
|
||||
_assert_enterprise_rejection(error.value)
|
||||
with pytest.raises(
|
||||
NotImplementedError, match="allow_external_blob_outside_bases"
|
||||
) as error:
|
||||
await db.create_table(
|
||||
"test",
|
||||
schema=schema,
|
||||
allow_external_blob_outside_bases=True,
|
||||
)
|
||||
_assert_enterprise_rejection(error.value)
|
||||
# The lower-layer guard still maps Error::NotSupported for direct native
|
||||
# calls that bypass the Python entrypoint.
|
||||
with pytest.raises(NotImplementedError, match="initial_bases"):
|
||||
await db._inner.create_table(
|
||||
"test",
|
||||
"create",
|
||||
reader(),
|
||||
initial_bases=[{"path": "s3://bucket/prefix"}],
|
||||
)
|
||||
with pytest.raises(
|
||||
NotImplementedError, match="allow_external_blob_outside_bases"
|
||||
):
|
||||
await db._inner.create_table(
|
||||
"test",
|
||||
"create",
|
||||
reader(),
|
||||
allow_external_blob_outside_bases=True,
|
||||
)
|
||||
|
||||
|
||||
def test_create_table_exist_ok():
|
||||
def handler(request):
|
||||
if request.path == "/v1/table/test/create/?mode=exist_ok":
|
||||
@@ -5887,6 +6013,9 @@ def blob_descriptor_take_table():
|
||||
)
|
||||
|
||||
|
||||
_DEFAULT_DESCRIPTOR_IDENTITY = object()
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
def blob_remote_table(
|
||||
*,
|
||||
@@ -5902,6 +6031,7 @@ def blob_remote_table(
|
||||
search_scores=False,
|
||||
snapshot_supported=True,
|
||||
identity_header="v1:" + "a" * 64,
|
||||
descriptor_identity_header=_DEFAULT_DESCRIPTOR_IDENTITY,
|
||||
verify_identity=True,
|
||||
):
|
||||
if state is None:
|
||||
@@ -5946,6 +6076,11 @@ def blob_remote_table(
|
||||
request.send_header(
|
||||
"x-lancedb-version", str(BLOB_DESCRIBE_RESPONSE["version"])
|
||||
)
|
||||
if verify_identity and request.headers.get("x-lancedb-query-snapshot"):
|
||||
request.send_header(
|
||||
"x-lancedb-query-snapshot",
|
||||
request.headers["x-lancedb-query-snapshot"],
|
||||
)
|
||||
request.end_headers()
|
||||
request.wfile.write(chunk)
|
||||
elif request.path == "/v1/table/test/query/":
|
||||
@@ -5954,14 +6089,26 @@ def blob_remote_table(
|
||||
if requests is not None:
|
||||
requests.append(("query", body))
|
||||
columns = body.get("columns")
|
||||
assert columns in (
|
||||
take_offsets_query = isinstance(columns, list) and "_rowoffset" in columns
|
||||
assert take_offsets_query or columns in (
|
||||
None,
|
||||
["id", "image"],
|
||||
["id"],
|
||||
["image"],
|
||||
{"payload": "image"},
|
||||
)
|
||||
if isinstance(columns, dict):
|
||||
if take_offsets_query:
|
||||
response_table = blob_query_response_table().append_column(
|
||||
"_rowoffset", pa.array(range(3), type=pa.uint64())
|
||||
)
|
||||
response_table = response_table.select(
|
||||
[name for name in columns if name != "_rowid"]
|
||||
)
|
||||
if body.get("with_row_id", False):
|
||||
response_table = response_table.append_column(
|
||||
"_rowid", blob_query_response_table()["_rowid"]
|
||||
)
|
||||
elif isinstance(columns, dict):
|
||||
response_table = blob_query_response_table().select(["image", "_rowid"])
|
||||
response_table = response_table.rename_columns(["payload", "_rowid"])
|
||||
if not body.get("with_row_id", False):
|
||||
@@ -6012,11 +6159,20 @@ def blob_remote_table(
|
||||
request.send_header("x-lancedb-version", header)
|
||||
if snapshot_supported:
|
||||
request.send_header("x-lancedb-query-version", header)
|
||||
identity = (
|
||||
identity_header(body)
|
||||
if callable(identity_header)
|
||||
else identity_header
|
||||
descriptor_query = body.get("filter", "").startswith("_rowid IN")
|
||||
use_descriptor_identity = (
|
||||
descriptor_query
|
||||
and descriptor_identity_header
|
||||
is not _DEFAULT_DESCRIPTOR_IDENTITY
|
||||
)
|
||||
if use_descriptor_identity:
|
||||
identity = descriptor_identity_header
|
||||
else:
|
||||
identity = (
|
||||
identity_header(body)
|
||||
if callable(identity_header)
|
||||
else identity_header
|
||||
)
|
||||
if identity is not None:
|
||||
request.send_header("x-lancedb-query-snapshot", identity)
|
||||
request.end_headers()
|
||||
@@ -6564,13 +6720,114 @@ def test_remote_blob_file_matches_file_error_and_range_contract():
|
||||
handle.read(1)
|
||||
|
||||
|
||||
def test_remote_blob_fetch_accepts_query_table():
|
||||
@pytest.mark.parametrize("api", ["fetch_blobs", "fetch_blob_files"])
|
||||
def test_remote_blob_fetch_accepts_metadata_free_query_table(api):
|
||||
hits = pa.table({"_rowid": pa.array([10, 20, 30], type=pa.uint64())})
|
||||
|
||||
with blob_remote_table() as table:
|
||||
blobs = table.fetch_blobs("image", hits)
|
||||
with blob_remote_table(descriptor_identity_header=None) as table:
|
||||
if api == "fetch_blobs":
|
||||
assert table.fetch_blobs("image", hits).to_pylist() == [
|
||||
b"alpha",
|
||||
None,
|
||||
b"gamma",
|
||||
]
|
||||
else:
|
||||
handles = table.fetch_blob_files("image", hits)
|
||||
try:
|
||||
assert [
|
||||
handle.read() if handle is not None else None for handle in handles
|
||||
] == [b"alpha", None, b"gamma"]
|
||||
finally:
|
||||
for handle in handles:
|
||||
if handle is not None:
|
||||
handle.close()
|
||||
|
||||
assert blobs.to_pylist() == [b"alpha", None, b"gamma"]
|
||||
|
||||
def test_remote_take_offsets_preserve_order_with_blob_bytes():
|
||||
with blob_remote_table() as table:
|
||||
hits = (
|
||||
table.take_offsets([2, 0, 2], preserve_order=True)
|
||||
.select(["id", "image"])
|
||||
.to_arrow(blob_mode="bytes")
|
||||
)
|
||||
|
||||
assert hits["id"].to_pylist() == [3, 1, 3]
|
||||
assert hits["image"].to_pylist() == [b"gamma", b"alpha", b"gamma"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("api", ["fetch_blobs", "fetch_blob_files"])
|
||||
def test_remote_blob_fetch_from_query_result_keeps_query_snapshot(api):
|
||||
requests = []
|
||||
state = {"version": 1}
|
||||
with blob_remote_table(requests=requests, state=state) as table:
|
||||
hits = table.search().select(["id", "image"]).limit(3).to_arrow()
|
||||
assert hits.schema.metadata[b"lancedb:query_version"] == b"1"
|
||||
table.add([{"id": 4, "image": b"new-version"}])
|
||||
assert table.version == 2
|
||||
|
||||
if api == "fetch_blobs":
|
||||
assert table.fetch_blobs("image", hits).to_pylist() == [
|
||||
b"alpha",
|
||||
None,
|
||||
b"gamma",
|
||||
]
|
||||
fetches = [body for path, body in requests if path == "fetch_blobs"]
|
||||
assert fetches
|
||||
assert all(body["version"] == 1 for body in fetches)
|
||||
else:
|
||||
handles = table.fetch_blob_files("image", hits)
|
||||
try:
|
||||
assert [
|
||||
handle.read() if handle is not None else None for handle in handles
|
||||
] == [b"alpha", None, b"gamma"]
|
||||
finally:
|
||||
for handle in handles:
|
||||
if handle is not None:
|
||||
handle.close()
|
||||
descriptor_queries = [
|
||||
body
|
||||
for path, body in requests
|
||||
if path == "query" and body.get("filter", "").startswith("_rowid IN")
|
||||
]
|
||||
assert descriptor_queries
|
||||
assert all(body["version"] == 1 for body in descriptor_queries)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("descriptor_identity", [None, "v1:" + "b" * 64])
|
||||
def test_remote_blob_files_reject_unverified_descriptor_identity(descriptor_identity):
|
||||
requested = "v1:" + "a" * 64
|
||||
hits = pa.table(
|
||||
{"_rowid": pa.array([20, 40], type=pa.uint64())}
|
||||
).replace_schema_metadata(
|
||||
{
|
||||
b"lancedb:query_version": b"1",
|
||||
b"lancedb:query_snapshot": requested.encode(),
|
||||
}
|
||||
)
|
||||
requests = []
|
||||
|
||||
with blob_remote_table(
|
||||
requests=requests, descriptor_identity_header=descriptor_identity
|
||||
) as table:
|
||||
with pytest.raises(
|
||||
NotImplementedError, match="did not verify the query snapshot identity"
|
||||
):
|
||||
table.fetch_blob_files("image", hits)
|
||||
|
||||
assert not any(path.startswith("/v1/table/test/blob/") for path, _ in requests)
|
||||
assert not any(path == "/v1/table/test/fetch_blobs/" for path, _ in requests)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("api", ["fetch_blobs", "fetch_blob_files"])
|
||||
def test_remote_blob_fetch_rejects_incomplete_query_snapshot(api):
|
||||
requests = []
|
||||
hits = pa.table(
|
||||
{"_rowid": pa.array([10], type=pa.uint64())}
|
||||
).replace_schema_metadata({b"lancedb:query_version": b"1"})
|
||||
with blob_remote_table(requests=requests) as table:
|
||||
with pytest.raises(NotImplementedError, match="x-lancedb-query-snapshot"):
|
||||
getattr(table, api)("image", hits)
|
||||
assert not any(path == "fetch_blobs" for path, _ in requests)
|
||||
|
||||
|
||||
def test_remote_blob_query_stashes_row_ids_for_fetch():
|
||||
|
||||
@@ -0,0 +1,160 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
import signal
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
from datetime import timedelta
|
||||
|
||||
import pyarrow as pa
|
||||
import pytest
|
||||
|
||||
import lancedb
|
||||
from lancedb import background_loop
|
||||
from lancedb.index import BTree, FTS, IvfFlat
|
||||
|
||||
|
||||
def _direct_query_table(tmp_path):
|
||||
table = lancedb.connect(tmp_path).create_table(
|
||||
"direct",
|
||||
pa.table(
|
||||
{
|
||||
"id": pa.array([1, 2, 3, 4], pa.int64()),
|
||||
"text": ["alpha beta", "alpha gamma", "beta gamma", "delta epsilon"],
|
||||
"vector": pa.array(
|
||||
[
|
||||
[1.0, 0.0, 0.0, 0.0],
|
||||
[0.0, 1.0, 0.0, 0.0],
|
||||
[0.0, 0.0, 1.0, 0.0],
|
||||
[0.0, 0.0, 0.0, 1.0],
|
||||
],
|
||||
pa.list_(pa.float32(), 4),
|
||||
),
|
||||
}
|
||||
),
|
||||
)
|
||||
table.create_index("id", config=BTree())
|
||||
table.create_index("vector", config=IvfFlat(distance_type="l2", num_partitions=1))
|
||||
table.create_index("text", config=FTS(with_position=True))
|
||||
return table
|
||||
|
||||
|
||||
def test_direct_sync_queries_do_not_use_background_loop(tmp_path, monkeypatch):
|
||||
table = _direct_query_table(tmp_path)
|
||||
expected_empty_schema = table.search().where("id < 0").output_schema()
|
||||
|
||||
def fail(*_args, **_kwargs):
|
||||
raise AssertionError("LOOP.run must not be used by direct sync queries")
|
||||
|
||||
monkeypatch.setattr(background_loop.LOOP, "run", fail)
|
||||
|
||||
point = table.search().where("id = 1").select(["id", "text"]).to_arrow()
|
||||
assert point.to_pylist() == [{"id": 1, "text": "alpha beta"}]
|
||||
|
||||
with_row_id = (
|
||||
table.search().where("id = 1").select(["id"]).with_row_id(True).to_arrow()
|
||||
)
|
||||
assert with_row_id["_rowid"].to_pylist() == [0]
|
||||
|
||||
# The vector column is inferred from the sync schema binding.
|
||||
vector = table.search([0.9, 0.1, 0.0, 0.0]).limit(2).to_arrow()
|
||||
assert vector["id"].to_pylist() == [1, 2]
|
||||
assert "_distance" in vector.column_names
|
||||
|
||||
fts = table.search("alpha", query_type="fts").select(["id"]).to_arrow()
|
||||
assert sorted(fts["id"].to_pylist()) == [1, 2]
|
||||
assert "_score" in fts.column_names
|
||||
|
||||
phrase = table.search('"alpha beta"', query_type="fts").select(["id"]).to_arrow()
|
||||
assert phrase["id"].to_pylist() == [1]
|
||||
|
||||
empty = table.search().where("id < 0").to_arrow()
|
||||
assert empty.num_rows == 0
|
||||
assert empty.schema == expected_empty_schema
|
||||
|
||||
with pytest.raises(Exception, match="Query timeout"):
|
||||
table.search([1.0, 0.0, 0.0, 0.0]).to_arrow(timeout=timedelta(0))
|
||||
|
||||
|
||||
@pytest.mark.skipif(sys.platform != "linux", reason="needs sched_setaffinity")
|
||||
def test_direct_sync_query_from_single_worker_progress_callback(tmp_path):
|
||||
script = r"""
|
||||
import os
|
||||
import sys
|
||||
|
||||
try:
|
||||
cpus = sorted(os.sched_getaffinity(0))
|
||||
if not cpus:
|
||||
print("SKIP")
|
||||
sys.exit(0)
|
||||
os.sched_setaffinity(0, {cpus[0]})
|
||||
except OSError:
|
||||
print("SKIP")
|
||||
sys.exit(0)
|
||||
|
||||
import lancedb
|
||||
|
||||
db = lancedb.connect("memory:///")
|
||||
target = db.create_table(
|
||||
"target",
|
||||
[{"id": 1, "value": "one"}, {"id": 2, "value": "two"}],
|
||||
)
|
||||
source = db.create_table("source", [{"id": 1}])
|
||||
seen = []
|
||||
|
||||
def progress(_update):
|
||||
if not seen:
|
||||
seen.append(
|
||||
target.search()
|
||||
.where("id = 1")
|
||||
.select(["value"])
|
||||
.to_arrow()
|
||||
.to_pylist()
|
||||
)
|
||||
|
||||
source.add([{"id": 2}], progress=progress)
|
||||
assert seen == [[{"value": "one"}]], seen
|
||||
print("OK")
|
||||
"""
|
||||
result = subprocess.run(
|
||||
[sys.executable, "-c", script],
|
||||
cwd=tmp_path,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=30,
|
||||
)
|
||||
if "SKIP" in result.stdout:
|
||||
pytest.skip("sched_setaffinity did not leave a usable CPU")
|
||||
assert result.returncode == 0, result.stdout + result.stderr
|
||||
assert "OK" in result.stdout
|
||||
|
||||
|
||||
@pytest.mark.slow
|
||||
def test_direct_sync_query_sigint_aborts_and_reuses_runtime(tmp_path):
|
||||
rows = 500_000
|
||||
table = lancedb.connect(tmp_path).create_table(
|
||||
"sigint",
|
||||
pa.table(
|
||||
{
|
||||
"id": pa.array(range(rows), pa.int64()),
|
||||
"text": pa.array([f"row-{row}" for row in range(rows)]),
|
||||
}
|
||||
),
|
||||
)
|
||||
# Warm the runtime and page cache so the timed call is long enough to observe.
|
||||
table.search().select(["id"]).to_arrow()
|
||||
|
||||
timer = threading.Timer(0.001, os.kill, args=(os.getpid(), signal.SIGINT))
|
||||
timer.start()
|
||||
try:
|
||||
with pytest.raises(KeyboardInterrupt):
|
||||
table.search().select(["id", "text"]).to_arrow()
|
||||
finally:
|
||||
timer.cancel()
|
||||
timer.join()
|
||||
|
||||
# The shared runtime and its generation counter remain usable.
|
||||
after = table.search().where("id = 1").select(["id", "text"]).to_arrow()
|
||||
assert after.to_pylist() == [{"id": 1, "text": "row-1"}]
|
||||
@@ -8,13 +8,15 @@ import json
|
||||
import multiprocessing as mp
|
||||
import pickle
|
||||
import re
|
||||
import struct
|
||||
import sys
|
||||
|
||||
import lancedb
|
||||
import numpy as np
|
||||
import pyarrow as pa
|
||||
import pytest
|
||||
from lancedb.permutation import Permutation, Permutations, permutation_builder
|
||||
from lancedb.util import tbl_to_tensor
|
||||
from lancedb.util import batch_to_tensor, batch_to_tensor_columns, tbl_to_tensor
|
||||
from utils import start_server_thread
|
||||
|
||||
torch = pytest.importorskip("torch")
|
||||
@@ -23,6 +25,43 @@ torch = pytest.importorskip("torch")
|
||||
REMOTE_ROWS = list(range(100))
|
||||
|
||||
|
||||
def _identity_collate(batch):
|
||||
return batch
|
||||
|
||||
|
||||
class _LanceBFloat16Type(pa.ExtensionType):
|
||||
def __init__(self):
|
||||
pa.ExtensionType.__init__(self, pa.binary(2), "lance.bfloat16")
|
||||
|
||||
def __arrow_ext_serialize__(self):
|
||||
return b""
|
||||
|
||||
@classmethod
|
||||
def __arrow_ext_deserialize__(cls, storage_type, serialized):
|
||||
return cls()
|
||||
|
||||
|
||||
def _bf16_storage(values):
|
||||
bits = torch.tensor(values, dtype=torch.bfloat16).view(torch.int16).tolist()
|
||||
return [struct.pack("<H", bit & 0xFFFF) for bit in bits]
|
||||
|
||||
|
||||
def _bf16_array(values):
|
||||
storage = pa.array(_bf16_storage(values), type=pa.binary(2))
|
||||
return pa.ExtensionArray.from_storage(_LanceBFloat16Type(), storage)
|
||||
|
||||
|
||||
def _fixed_shape_tensor_array(physical_values, shape, permutation=None):
|
||||
tensor_type = pa.fixed_shape_tensor(
|
||||
pa.float32(), shape, permutation=permutation or []
|
||||
)
|
||||
flat_values = np.asarray(physical_values, dtype=np.float32).reshape(-1)
|
||||
storage = pa.FixedSizeListArray.from_arrays(
|
||||
pa.array(flat_values), int(np.prod(shape))
|
||||
)
|
||||
return pa.ExtensionArray.from_storage(tensor_type, storage)
|
||||
|
||||
|
||||
def _make_mock_http_handler(handler):
|
||||
class MockLanceDBHandler(http.server.BaseHTTPRequestHandler):
|
||||
def do_GET(self):
|
||||
@@ -496,3 +535,472 @@ def test_remote_permutation_dataloader_fork_workers():
|
||||
finally:
|
||||
server.shutdown()
|
||||
handle.join()
|
||||
|
||||
|
||||
def test_permutation_torch_dict_mixed_columns(mem_db):
|
||||
vectors = [[float(i), float(i) + 0.5, float(i) + 1.0] for i in range(5)]
|
||||
grids = [
|
||||
[[float(row), float(row) + 1.0], [float(row) + 2.0, float(row) + 3.0]]
|
||||
for row in range(5)
|
||||
]
|
||||
table = mem_db.create_table(
|
||||
"mixed",
|
||||
pa.table(
|
||||
{
|
||||
"id": pa.array(range(5), type=pa.int32()),
|
||||
"score": pa.array([i / 2 for i in range(5)], type=pa.float32()),
|
||||
"vector": pa.array(vectors, type=pa.list_(pa.float32(), 3)),
|
||||
"grid": pa.array(grids, type=pa.list_(pa.list_(pa.float32(), 2), 2)),
|
||||
}
|
||||
),
|
||||
)
|
||||
permutation = Permutation.identity(table).with_format("torch_dict")
|
||||
|
||||
batch = next(permutation.iter(5, skip_last_batch=False))
|
||||
assert set(batch) == {"id", "score", "vector", "grid"}
|
||||
assert batch["id"].shape == (5,)
|
||||
assert batch["id"].dtype == torch.int32
|
||||
assert batch["score"].dtype == torch.float32
|
||||
assert batch["vector"].shape == (5, 3)
|
||||
assert batch["grid"].shape == (5, 2, 2)
|
||||
assert torch.equal(batch["vector"], torch.tensor(vectors))
|
||||
assert torch.equal(batch["grid"], torch.tensor(grids))
|
||||
|
||||
items = permutation.__getitems__([0, 2, 4])
|
||||
assert items["id"].shape == (3,)
|
||||
assert items["score"].shape == (3,)
|
||||
assert items["vector"].shape == (3, 3)
|
||||
assert items["grid"].shape == (3, 2, 2)
|
||||
|
||||
dataloader = torch.utils.data.DataLoader(
|
||||
permutation,
|
||||
batch_size=2,
|
||||
shuffle=False,
|
||||
collate_fn=_identity_collate,
|
||||
)
|
||||
batches = list(dataloader)
|
||||
assert [batch["id"].shape[0] for batch in batches] == [2, 2, 1]
|
||||
assert batches[0]["vector"].shape == (2, 3)
|
||||
assert batches[-1]["grid"].shape == (1, 2, 2)
|
||||
|
||||
empty = permutation.take_offsets([])
|
||||
assert empty["id"].shape == (0,)
|
||||
assert empty["vector"].shape == (0, 3)
|
||||
assert empty["grid"].shape == (0, 2, 2)
|
||||
|
||||
torch_permutation = Permutation.identity(table).with_format("torch")
|
||||
per_row = next(torch_permutation.iter(2, skip_last_batch=False))
|
||||
assert isinstance(per_row, list)
|
||||
assert per_row[0]["vector"].shape == (3,)
|
||||
assert per_row[0]["grid"].shape == (2, 2)
|
||||
torch_loader = torch.utils.data.DataLoader(
|
||||
torch_permutation, batch_size=2, shuffle=False
|
||||
)
|
||||
collated = next(iter(torch_loader))
|
||||
assert collated["vector"].shape == (2, 3)
|
||||
assert collated["grid"].shape == (2, 2, 2)
|
||||
|
||||
|
||||
def test_permutation_torch_dict_dataloader_spawn(tmp_db):
|
||||
vectors = [[float(i), float(i) + 0.5] for i in range(11)]
|
||||
table = tmp_db.create_table(
|
||||
"spawn",
|
||||
pa.table(
|
||||
{
|
||||
"id": range(11),
|
||||
"vector": pa.array(vectors, type=pa.list_(pa.float32(), 2)),
|
||||
}
|
||||
),
|
||||
)
|
||||
permutation = Permutation.identity(table).with_format("torch_dict")
|
||||
|
||||
dataloader = torch.utils.data.DataLoader(
|
||||
permutation,
|
||||
batch_size=4,
|
||||
shuffle=False,
|
||||
num_workers=2,
|
||||
multiprocessing_context="spawn",
|
||||
collate_fn=_identity_collate,
|
||||
)
|
||||
seen = []
|
||||
for batch in dataloader:
|
||||
assert isinstance(batch, dict)
|
||||
assert batch["id"].shape == (batch["id"].shape[0],)
|
||||
assert batch["vector"].shape == (batch["id"].shape[0], 2)
|
||||
seen.extend(batch["id"].tolist())
|
||||
assert sorted(seen) == list(range(11))
|
||||
|
||||
|
||||
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)
|
||||
batch = pa.record_batch(
|
||||
[
|
||||
pa.array(range(5), type=pa.int64()),
|
||||
pa.array(vectors, type=pa.list_(pa.float32(), 3)),
|
||||
pa.array(
|
||||
nested_values.tolist(),
|
||||
type=pa.list_(pa.list_(pa.float32(), 2), 3),
|
||||
),
|
||||
pa.array([True, False, True, False, True]),
|
||||
],
|
||||
names=["id", "vector", "nested", "active"],
|
||||
).slice(2, 2)
|
||||
|
||||
tensors = batch_to_tensor_columns(batch)
|
||||
assert tensors["id"].tolist() == [2, 3]
|
||||
assert torch.equal(tensors["vector"], torch.tensor(vectors[2:4]))
|
||||
assert torch.equal(tensors["nested"], torch.from_numpy(nested_values[2:4].copy()))
|
||||
assert tensors["active"].dtype == torch.bool
|
||||
assert tensors["active"].tolist() == [True, False]
|
||||
|
||||
id_array = batch.column("id")
|
||||
assert tensors["id"].data_ptr() == (
|
||||
id_array.buffers()[1].address + id_array.offset * 8
|
||||
)
|
||||
vector_array = batch.column("vector")
|
||||
vector_values = vector_array.values
|
||||
expected_vector_offset = (vector_array.offset * 3 + vector_values.offset) * 4
|
||||
assert tensors["vector"].data_ptr() == (
|
||||
vector_values.buffers()[1].address + expected_vector_offset
|
||||
)
|
||||
|
||||
single_column = pa.record_batch([batch.column("vector")], names=["vector"])
|
||||
column_tensor = batch_to_tensor(single_column)
|
||||
assert column_tensor.shape == (1, 2, 3)
|
||||
assert column_tensor.data_ptr() == tensors["vector"].data_ptr()
|
||||
|
||||
|
||||
def test_permutation_torch_col_and_row_vector_layouts(mem_db):
|
||||
left = [[float(i), float(i) + 0.5] for i in range(4)]
|
||||
right = [[float(i) + 1.0, float(i) + 1.5] for i in range(4)]
|
||||
table = mem_db.create_table(
|
||||
"uniform",
|
||||
pa.table(
|
||||
{
|
||||
"left": pa.array(left, type=pa.list_(pa.float32(), 2)),
|
||||
"right": pa.array(right, type=pa.list_(pa.float32(), 2)),
|
||||
}
|
||||
),
|
||||
)
|
||||
permutation = Permutation.identity(table)
|
||||
|
||||
column_batch = next(
|
||||
permutation.with_format("torch_col").iter(4, skip_last_batch=False)
|
||||
)
|
||||
assert column_batch.shape == (2, 4, 2)
|
||||
assert column_batch.dtype == torch.float32
|
||||
assert torch.equal(column_batch[0], torch.tensor(left))
|
||||
|
||||
row_batch = next(
|
||||
permutation.with_format("torch_row").iter(4, skip_last_batch=False)
|
||||
)
|
||||
assert len(row_batch) == 4
|
||||
assert row_batch[0].shape == (2, 2)
|
||||
assert torch.equal(
|
||||
row_batch[0], torch.stack([torch.tensor(left[0]), torch.tensor(right[0])])
|
||||
)
|
||||
|
||||
dataloader = torch.utils.data.DataLoader(
|
||||
permutation.with_format("torch_row"), batch_size=4, shuffle=False
|
||||
)
|
||||
stacked = next(iter(dataloader))
|
||||
assert stacked.shape == (4, 2, 2)
|
||||
|
||||
scalar_table = mem_db.create_table(
|
||||
"single_scalar", pa.table({"x": pa.array(range(4), type=pa.int64())})
|
||||
)
|
||||
scalar_rows = next(
|
||||
Permutation.identity(scalar_table)
|
||||
.with_format("torch_row")
|
||||
.iter(4, skip_last_batch=False)
|
||||
)
|
||||
assert scalar_rows[0].shape == (1,)
|
||||
assert scalar_rows[0].dtype == torch.int64
|
||||
|
||||
vector_table = mem_db.create_table(
|
||||
"single_vector",
|
||||
pa.table({"v": pa.array(left, type=pa.list_(pa.float32(), 2))}),
|
||||
)
|
||||
vector_rows = next(
|
||||
Permutation.identity(vector_table)
|
||||
.with_format("torch_row")
|
||||
.iter(4, skip_last_batch=False)
|
||||
)
|
||||
assert vector_rows[0].shape == (1, 2)
|
||||
vector_column = next(
|
||||
Permutation.identity(vector_table)
|
||||
.with_format("torch_col")
|
||||
.iter(4, skip_last_batch=False)
|
||||
)
|
||||
assert vector_column.shape == (1, 4, 2)
|
||||
|
||||
|
||||
def test_torch_col_and_row_reject_heterogeneous_shapes(mem_db):
|
||||
table = mem_db.create_table(
|
||||
"heterogeneous",
|
||||
pa.table(
|
||||
{
|
||||
"id": pa.array(range(4), type=pa.int64()),
|
||||
"vector": pa.array(
|
||||
[[float(i), float(i) + 1.0, float(i) + 2.0] for i in range(4)],
|
||||
type=pa.list_(pa.float32(), 3),
|
||||
),
|
||||
}
|
||||
),
|
||||
)
|
||||
permutation = Permutation.identity(table)
|
||||
for format_name in ("torch_col", "torch_row"):
|
||||
with pytest.raises(ValueError, match="torch_dict") as exc_info:
|
||||
next(permutation.with_format(format_name).iter(2, skip_last_batch=False))
|
||||
message = str(exc_info.value)
|
||||
assert "`vector`" in message
|
||||
assert "(3,)" in message
|
||||
assert "`id`" in message
|
||||
assert "()" in message
|
||||
|
||||
different_dims = mem_db.create_table(
|
||||
"different_dims",
|
||||
pa.table(
|
||||
{
|
||||
"left": pa.array(
|
||||
[[1.0, 2.0] for _ in range(4)],
|
||||
type=pa.list_(pa.float32(), 2),
|
||||
),
|
||||
"right": pa.array(
|
||||
[[1.0, 2.0, 3.0] for _ in range(4)],
|
||||
type=pa.list_(pa.float32(), 3),
|
||||
),
|
||||
}
|
||||
),
|
||||
)
|
||||
with pytest.raises(ValueError, match="torch_dict") as exc_info:
|
||||
next(
|
||||
Permutation.identity(different_dims)
|
||||
.with_format("torch_row")
|
||||
.iter(2, skip_last_batch=False)
|
||||
)
|
||||
message = str(exc_info.value)
|
||||
assert "`right`" in message and "(3,)" in message
|
||||
assert "`left`" in message and "(2,)" in message
|
||||
|
||||
|
||||
def test_torch_row_uses_pytorch_numeric_promotion(mem_db):
|
||||
table = mem_db.create_table(
|
||||
"promotion",
|
||||
pa.table(
|
||||
{
|
||||
"id": pa.array(range(4), type=pa.int64()),
|
||||
"score": pa.array([i / 2 for i in range(4)], type=pa.float32()),
|
||||
"count": pa.array(range(4), type=pa.int32()),
|
||||
}
|
||||
),
|
||||
)
|
||||
rows = next(
|
||||
Permutation.identity(table)
|
||||
.with_format("torch_row")
|
||||
.iter(4, skip_last_batch=False)
|
||||
)
|
||||
assert rows[0].shape == (3,)
|
||||
assert rows[0].dtype == torch.float32
|
||||
assert rows[0].tolist() == [0.0, 0.0, 0.0]
|
||||
assert rows[2].tolist() == [2.0, 1.0, 2.0]
|
||||
|
||||
|
||||
def test_torch_row_preserves_nullable_numeric_scalar_nan(mem_db):
|
||||
nullable_int = mem_db.create_table(
|
||||
"nullable_int",
|
||||
pa.table({"value": pa.array([1, None, 3], type=pa.int64())}),
|
||||
)
|
||||
rows = next(
|
||||
Permutation.identity(nullable_int)
|
||||
.with_format("torch_row")
|
||||
.iter(3, skip_last_batch=False)
|
||||
)
|
||||
assert rows[0].shape == (1,)
|
||||
assert rows[0].dtype == torch.float64
|
||||
assert rows[0].tolist() == [1.0]
|
||||
assert torch.isnan(rows[1]).all()
|
||||
assert rows[2].tolist() == [3.0]
|
||||
|
||||
nullable_float = mem_db.create_table(
|
||||
"nullable_float",
|
||||
pa.table({"value": pa.array([0.5, None, 2.5], type=pa.float32())}),
|
||||
)
|
||||
rows = next(
|
||||
Permutation.identity(nullable_float)
|
||||
.with_format("torch_row")
|
||||
.iter(3, skip_last_batch=False)
|
||||
)
|
||||
assert rows[0].dtype == torch.float32
|
||||
assert rows[0].tolist() == [0.5]
|
||||
assert torch.isnan(rows[1]).all()
|
||||
assert rows[2].tolist() == [2.5]
|
||||
|
||||
nullable_mixed = mem_db.create_table(
|
||||
"nullable_mixed",
|
||||
pa.table(
|
||||
{
|
||||
"id": pa.array([1, None, 3], type=pa.int64()),
|
||||
"score": pa.array([0.5, 1.5, 2.5], type=pa.float32()),
|
||||
}
|
||||
),
|
||||
)
|
||||
rows = next(
|
||||
Permutation.identity(nullable_mixed)
|
||||
.with_format("torch_row")
|
||||
.iter(3, skip_last_batch=False)
|
||||
)
|
||||
assert rows[0].dtype == torch.float64
|
||||
assert rows[0].tolist() == [1.0, 0.5]
|
||||
assert torch.isnan(rows[1][0])
|
||||
assert rows[1][1].item() == 1.5
|
||||
assert rows[2].tolist() == [3.0, 2.5]
|
||||
|
||||
|
||||
def test_permutation_torch_formats_fixed_shape_tensor_permutation(mem_db):
|
||||
physical_values = np.arange(2 * 2 * 3 * 4, dtype=np.float32).reshape(2, 2, 3, 4)
|
||||
tensor_array = _fixed_shape_tensor_array(
|
||||
physical_values, shape=(2, 3, 4), permutation=[0, 2, 1]
|
||||
)
|
||||
table = mem_db.create_table(
|
||||
"tensor_permutation",
|
||||
pa.table({"id": range(2), "tensor": tensor_array}),
|
||||
)
|
||||
permutation = Permutation.identity(table)
|
||||
expected = np.transpose(physical_values, (0, 1, 3, 2))
|
||||
|
||||
batch = next(permutation.with_format("torch_dict").iter(2, skip_last_batch=False))
|
||||
assert batch["tensor"].shape == (2, 2, 4, 3)
|
||||
assert torch.equal(batch["tensor"], torch.from_numpy(expected.copy()))
|
||||
|
||||
tensor_only = permutation.select_columns(["tensor"])
|
||||
rows = next(tensor_only.with_format("torch_row").iter(2, skip_last_batch=False))
|
||||
assert rows[0].shape == (1, 2, 4, 3)
|
||||
assert torch.equal(rows[0][0], torch.from_numpy(expected[0].copy()))
|
||||
|
||||
dataloader = torch.utils.data.DataLoader(
|
||||
tensor_only.with_format("torch"), batch_size=2, shuffle=False
|
||||
)
|
||||
default_collated = next(iter(dataloader))
|
||||
assert default_collated["tensor"].shape == (2, 2, 4, 3)
|
||||
|
||||
|
||||
def test_permutation_torch_formats_bfloat16(mem_db):
|
||||
values = [1.0, -1.5, 2.5, 0.0]
|
||||
scalar_values = _bf16_array(values)
|
||||
vector_values = pa.FixedSizeListArray.from_arrays(
|
||||
_bf16_array([value for value in values for _ in range(2)]), 2
|
||||
)
|
||||
table = mem_db.create_table(
|
||||
"bfloat16",
|
||||
pa.table(
|
||||
{
|
||||
"id": range(4),
|
||||
"scalar": scalar_values,
|
||||
"vector": vector_values,
|
||||
}
|
||||
),
|
||||
)
|
||||
permutation = Permutation.identity(table)
|
||||
|
||||
batch = next(permutation.with_format("torch_dict").iter(2, skip_last_batch=False))
|
||||
assert batch["scalar"].dtype == torch.bfloat16
|
||||
assert batch["vector"].dtype == torch.bfloat16
|
||||
assert torch.equal(batch["scalar"], torch.tensor(values[:2], dtype=torch.bfloat16))
|
||||
assert torch.equal(
|
||||
batch["vector"],
|
||||
torch.tensor([[value, value] for value in values[:2]], dtype=torch.bfloat16),
|
||||
)
|
||||
|
||||
arrow_batch = next(permutation.with_format("arrow").iter(2, skip_last_batch=False))
|
||||
arrow_tensors = batch_to_tensor_columns(arrow_batch)
|
||||
scalar_array = arrow_batch.column("scalar")
|
||||
assert arrow_tensors["scalar"].data_ptr() == (
|
||||
scalar_array.buffers()[1].address + scalar_array.offset * 2
|
||||
)
|
||||
|
||||
sliced = arrow_batch.slice(1, 1)
|
||||
sliced_tensors = batch_to_tensor_columns(sliced)
|
||||
assert torch.equal(
|
||||
sliced_tensors["scalar"],
|
||||
torch.tensor([values[1]], dtype=torch.bfloat16),
|
||||
)
|
||||
assert torch.equal(
|
||||
sliced_tensors["vector"],
|
||||
torch.tensor([[values[1], values[1]]], dtype=torch.bfloat16),
|
||||
)
|
||||
|
||||
skipped = next(
|
||||
permutation.with_skip(1)
|
||||
.with_format("torch_dict")
|
||||
.iter(2, skip_last_batch=False)
|
||||
)
|
||||
assert torch.equal(
|
||||
skipped["scalar"], torch.tensor(values[1:3], dtype=torch.bfloat16)
|
||||
)
|
||||
|
||||
empty = permutation.with_format("torch_dict").take_offsets([])
|
||||
assert empty["scalar"].shape == (0,)
|
||||
assert empty["scalar"].dtype == torch.bfloat16
|
||||
assert empty["vector"].shape == (0, 2)
|
||||
assert empty["vector"].dtype == torch.bfloat16
|
||||
|
||||
unmarked = mem_db.create_table(
|
||||
"unmarked_bfloat16",
|
||||
pa.table(
|
||||
{
|
||||
"vector": pa.FixedSizeListArray.from_arrays(
|
||||
pa.array(_bf16_storage(values), type=pa.binary(2)), 2
|
||||
)
|
||||
}
|
||||
),
|
||||
)
|
||||
with pytest.raises(ValueError, match="not marked.*lance.bfloat16"):
|
||||
next(
|
||||
Permutation.identity(unmarked)
|
||||
.with_format("torch_dict")
|
||||
.iter(2, skip_last_batch=False)
|
||||
)
|
||||
|
||||
|
||||
def test_torch_formats_reject_nulls(mem_db):
|
||||
parent_nulls = mem_db.create_table(
|
||||
"parent_nulls",
|
||||
pa.table(
|
||||
{
|
||||
"id": range(3),
|
||||
"values": pa.array(
|
||||
[[1.0, 2.0], None, [5.0, 6.0]],
|
||||
type=pa.list_(pa.float32(), 2),
|
||||
),
|
||||
}
|
||||
),
|
||||
)
|
||||
with pytest.raises(ValueError, match="contains 1 null"):
|
||||
next(
|
||||
Permutation.identity(parent_nulls)
|
||||
.with_format("torch_dict")
|
||||
.iter(2, skip_last_batch=False)
|
||||
)
|
||||
|
||||
leaf_nulls = mem_db.create_table(
|
||||
"leaf_nulls",
|
||||
pa.table(
|
||||
{
|
||||
"id": range(2),
|
||||
"values": pa.FixedSizeListArray.from_arrays(
|
||||
pa.array([1.0, None, 5.0, 6.0], type=pa.float32()), 2
|
||||
),
|
||||
}
|
||||
),
|
||||
)
|
||||
with pytest.raises(ValueError, match="contains 1 null"):
|
||||
next(
|
||||
Permutation.identity(leaf_nulls)
|
||||
.with_format("torch_dict")
|
||||
.iter(2, skip_last_batch=False)
|
||||
)
|
||||
leaf_only = Permutation.identity(leaf_nulls).select_columns(["values"])
|
||||
with pytest.raises(ValueError, match="contains 1 null"):
|
||||
next(leaf_only.with_format("torch_row").iter(2, skip_last_batch=False))
|
||||
|
||||
@@ -407,6 +407,33 @@ def test_value_to_sql_nan_and_infinity(tmp_path):
|
||||
assert rows[4]["f64"] == 4.0 and rows[4]["f32"] == 4.0
|
||||
|
||||
|
||||
def test_value_to_sql_enum_members(tmp_path):
|
||||
# str() of an int- or float-valued Enum member is its name, which SQL reads
|
||||
# as a field access, and a plain Enum member raised NotImplementedError.
|
||||
import enum
|
||||
|
||||
class Priority(int, enum.Enum):
|
||||
LOW = 1
|
||||
HIGH = 2
|
||||
|
||||
class Weight(float, enum.Enum):
|
||||
HALF = 0.5
|
||||
|
||||
class Color(enum.Enum):
|
||||
RED = "red"
|
||||
|
||||
assert value_to_sql(Priority.HIGH) == "2"
|
||||
assert value_to_sql(Weight.HALF) == "0.5"
|
||||
assert value_to_sql(Color.RED) == "'red'"
|
||||
|
||||
db = lancedb.connect(tmp_path)
|
||||
table = db.create_table(
|
||||
"test", pa.table({"id": [1], "p": [1], "w": [1.0], "c": ["blue"]})
|
||||
)
|
||||
table.update(values={"p": Priority.HIGH, "w": Weight.HALF, "c": Color.RED})
|
||||
assert table.to_arrow().to_pylist() == [{"id": 1, "p": 2, "w": 0.5, "c": "red"}]
|
||||
|
||||
|
||||
def test_append_vector_columns():
|
||||
registry = EmbeddingFunctionRegistry.get_instance()
|
||||
registry.register("test")(MockTextEmbeddingFunction)
|
||||
|
||||
@@ -120,7 +120,7 @@ def test_wal_hybrid_fuses_on_the_key_and_drops_it_again():
|
||||
with_row_ids=True,
|
||||
)
|
||||
results = builder._finish_hybrid_results(
|
||||
combined, blob_mode="lazy", blob_sources={}
|
||||
combined, blob_mode="lazy", blob_sources={}, schema=None
|
||||
)
|
||||
|
||||
assert "_rowid" not in results.column_names, "the surrogate is internal"
|
||||
|
||||
+40
-13
@@ -5,7 +5,7 @@ use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use crate::error::PythonErrorExt;
|
||||
use crate::runtime::future_into_py;
|
||||
use crate::runtime::{block_on_interruptible, future_into_py};
|
||||
use arrow::{
|
||||
array::RecordBatch,
|
||||
datatypes::SchemaRef,
|
||||
@@ -99,22 +99,49 @@ where
|
||||
Q: ExecutableQuery + Send + 'static,
|
||||
{
|
||||
future_into_py(py, async move {
|
||||
let mut options = QueryExecutionOptions::default();
|
||||
// `None` means the caller wants one eager result, not the core's
|
||||
// default batch size. An explicit value is still honored.
|
||||
options.max_batch_length = max_batch_length.unwrap_or(0);
|
||||
options.timeout = timeout;
|
||||
let stream = query.execute_with_options(options).await.infer_error()?;
|
||||
let schema = stream.schema();
|
||||
let batches = stream.try_collect::<Vec<_>>().await.infer_error()?;
|
||||
let reader: Box<dyn ArrowRecordBatchReader + Send> = Box::new(RecordBatchIterator::new(
|
||||
batches.into_iter().map(Ok),
|
||||
schema,
|
||||
));
|
||||
let reader = collect_to_reader(query, max_batch_length, timeout).await?;
|
||||
Python::attach(|py| reader.into_pyarrow(py).map(|obj| obj.unbind()))
|
||||
})
|
||||
}
|
||||
|
||||
/// Synchronous counterpart of [`execute_to_reader`].
|
||||
///
|
||||
/// The returned reader owns the collected batches; the caller converts it to
|
||||
/// Python after reattaching to the interpreter. The wait releases the GIL and
|
||||
/// keeps Python signal handlers on the calling thread.
|
||||
pub fn execute_to_reader_sync<Q>(
|
||||
query: Q,
|
||||
max_batch_length: Option<u32>,
|
||||
timeout: Option<Duration>,
|
||||
) -> PyResult<Box<dyn ArrowRecordBatchReader + Send>>
|
||||
where
|
||||
Q: ExecutableQuery + Send + 'static,
|
||||
{
|
||||
block_on_interruptible(collect_to_reader(query, max_batch_length, timeout))
|
||||
}
|
||||
|
||||
async fn collect_to_reader<Q>(
|
||||
query: Q,
|
||||
max_batch_length: Option<u32>,
|
||||
timeout: Option<Duration>,
|
||||
) -> PyResult<Box<dyn ArrowRecordBatchReader + Send>>
|
||||
where
|
||||
Q: ExecutableQuery + Send + 'static,
|
||||
{
|
||||
let mut options = QueryExecutionOptions::default();
|
||||
// `None` means the caller wants one eager result, not the core's
|
||||
// default batch size. An explicit value is still honored.
|
||||
options.max_batch_length = max_batch_length.unwrap_or(0);
|
||||
options.timeout = timeout;
|
||||
let stream = query.execute_with_options(options).await.infer_error()?;
|
||||
let schema = stream.schema();
|
||||
let batches = stream.try_collect::<Vec<_>>().await.infer_error()?;
|
||||
Ok(Box::new(RecordBatchIterator::new(
|
||||
batches.into_iter().map(Ok),
|
||||
schema,
|
||||
)))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
+152
-4
@@ -20,6 +20,7 @@ use arrow::{
|
||||
pyarrow::{FromPyArrow, PyArrowType, ToPyArrow},
|
||||
};
|
||||
use lancedb::{
|
||||
BasePath,
|
||||
connection::Connection as LanceConnection,
|
||||
connection::NamespaceClientPushdownOperation,
|
||||
database::namespace::LanceNamespaceDatabase,
|
||||
@@ -30,9 +31,9 @@ use lancedb::{
|
||||
};
|
||||
use pyo3::{
|
||||
Bound, FromPyObject, Py, PyAny, PyRef, PyResult, Python,
|
||||
exceptions::{PyRuntimeError, PyValueError},
|
||||
exceptions::{PyRuntimeError, PyTypeError, PyValueError},
|
||||
pyclass, pyfunction, pymethods,
|
||||
types::{PyAnyMethods, PyDict, PyDictMethods, PyList},
|
||||
types::{PyAnyMethods, PyBool, PyDict, PyDictMethods, PyList},
|
||||
};
|
||||
|
||||
fn materialized_view_builder(
|
||||
@@ -56,6 +57,139 @@ fn materialized_view_builder(
|
||||
}
|
||||
}
|
||||
|
||||
/// Parse `initial_bases` into Lance base paths.
|
||||
///
|
||||
/// Accepts LanceDB's lightweight `BasePath`, a mapping with the same keys, or
|
||||
/// a duck-typed `lance.DatasetBasePath`. `None` maps to no bases. Object
|
||||
/// attributes follow `DatasetBasePath`: a reported `id` of `0` means
|
||||
/// automatic assignment, while a mapping that sets `id=0` explicitly is
|
||||
/// rejected because `0` is reserved for unregistered blob URIs. Explicit
|
||||
/// non-zero ids must be unique.
|
||||
fn parse_initial_bases(initial_bases: Option<Bound<'_, PyAny>>) -> PyResult<Option<Vec<BasePath>>> {
|
||||
let Some(value) = initial_bases else {
|
||||
return Ok(None);
|
||||
};
|
||||
if value.is_none() {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
let mut bases = Vec::new();
|
||||
let mut explicit_ids: HashSet<u32> = HashSet::new();
|
||||
for (index, item) in value.try_iter()?.enumerate() {
|
||||
let item = item?;
|
||||
let base = parse_base_path(&item, index)?;
|
||||
if base.id != 0 && !explicit_ids.insert(base.id) {
|
||||
return Err(PyValueError::new_err(format!(
|
||||
"initial_bases[{index}] reuses base id {}; explicit ids must be unique",
|
||||
base.id
|
||||
)));
|
||||
}
|
||||
bases.push(base);
|
||||
}
|
||||
Ok(Some(bases))
|
||||
}
|
||||
|
||||
fn parse_base_path(item: &Bound<'_, PyAny>, index: usize) -> PyResult<BasePath> {
|
||||
let (path, name, is_dataset_root, id) = if let Ok(dict) = item.cast::<PyDict>() {
|
||||
let path = required_string(dict.get_item("path")?, index, "path")?;
|
||||
let name = optional_string(dict.get_item("name")?, index, "name")?;
|
||||
let is_dataset_root =
|
||||
optional_bool(dict.get_item("is_dataset_root")?, index, "is_dataset_root")?;
|
||||
let id = match dict.get_item("id")? {
|
||||
None => 0,
|
||||
Some(value) if value.is_none() => 0,
|
||||
Some(value) => {
|
||||
let id = base_id(&value, index)?;
|
||||
if id == 0 {
|
||||
return Err(PyValueError::new_err(format!(
|
||||
"initial_bases[{index}] sets id=0, which is reserved for unregistered \
|
||||
blob URIs; pass id=None to let Lance assign an ID"
|
||||
)));
|
||||
}
|
||||
id
|
||||
}
|
||||
};
|
||||
(path, name, is_dataset_root, id)
|
||||
} else {
|
||||
let path = item.getattr("path").map_err(|_| {
|
||||
PyTypeError::new_err(format!(
|
||||
"initial_bases[{index}] must be a BasePath, dict, or DatasetBasePath"
|
||||
))
|
||||
})?;
|
||||
let path = required_string(Some(path), index, "path")?;
|
||||
let name = item.getattr("name").ok().filter(|value| !value.is_none());
|
||||
let name = optional_string(name, index, "name")?;
|
||||
let is_dataset_root = match item.getattr("is_dataset_root") {
|
||||
Ok(value) if !value.is_none() => value.extract::<bool>().map_err(|_| {
|
||||
PyTypeError::new_err(format!(
|
||||
"initial_bases[{index}].is_dataset_root must be a bool"
|
||||
))
|
||||
})?,
|
||||
_ => false,
|
||||
};
|
||||
let id = match item.getattr("id") {
|
||||
Ok(value) if !value.is_none() => base_id(&value, index)?,
|
||||
_ => 0,
|
||||
};
|
||||
(path, name, is_dataset_root, id)
|
||||
};
|
||||
|
||||
if path.is_empty() {
|
||||
return Err(PyValueError::new_err(format!(
|
||||
"initial_bases[{index}].path must not be empty"
|
||||
)));
|
||||
}
|
||||
Ok(BasePath::new(id, path, name, is_dataset_root))
|
||||
}
|
||||
|
||||
fn required_string(value: Option<Bound<'_, PyAny>>, index: usize, field: &str) -> PyResult<String> {
|
||||
let Some(value) = value else {
|
||||
return Err(PyValueError::new_err(format!(
|
||||
"initial_bases[{index}] is missing '{field}'"
|
||||
)));
|
||||
};
|
||||
value.extract::<String>().map_err(|_| {
|
||||
PyTypeError::new_err(format!("initial_bases[{index}].{field} must be a string"))
|
||||
})
|
||||
}
|
||||
|
||||
fn optional_string(
|
||||
value: Option<Bound<'_, PyAny>>,
|
||||
index: usize,
|
||||
field: &str,
|
||||
) -> PyResult<Option<String>> {
|
||||
match value {
|
||||
None => Ok(None),
|
||||
Some(value) if value.is_none() => Ok(None),
|
||||
Some(value) => value.extract::<String>().map(Some).map_err(|_| {
|
||||
PyTypeError::new_err(format!("initial_bases[{index}].{field} must be a string"))
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
fn optional_bool(value: Option<Bound<'_, PyAny>>, index: usize, field: &str) -> PyResult<bool> {
|
||||
match value {
|
||||
None => Ok(false),
|
||||
Some(value) if value.is_none() => Ok(false),
|
||||
Some(value) => value.extract::<bool>().map_err(|_| {
|
||||
PyTypeError::new_err(format!("initial_bases[{index}].{field} must be a bool"))
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
fn base_id(value: &Bound<'_, PyAny>, index: usize) -> PyResult<u32> {
|
||||
if value.is_instance_of::<PyBool>() {
|
||||
return Err(PyTypeError::new_err(format!(
|
||||
"initial_bases[{index}].id must be a positive integer, not a bool"
|
||||
)));
|
||||
}
|
||||
value.extract::<u32>().map_err(|_| {
|
||||
PyValueError::new_err(format!(
|
||||
"initial_bases[{index}].id must be a positive integer that fits in a u32"
|
||||
))
|
||||
})
|
||||
}
|
||||
|
||||
#[pyclass]
|
||||
pub struct Connection {
|
||||
inner: Option<LanceConnection>,
|
||||
@@ -311,7 +445,7 @@ impl Connection {
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
#[pyo3(signature = (name, mode, data, namespace_path=None, storage_options=None, location=None, namespace_client=None))]
|
||||
#[pyo3(signature = (name, mode, data, namespace_path=None, storage_options=None, location=None, namespace_client=None, initial_bases=None, allow_external_blob_outside_bases=false))]
|
||||
pub fn create_table<'a>(
|
||||
self_: PyRef<'a, Self>,
|
||||
name: String,
|
||||
@@ -321,11 +455,14 @@ impl Connection {
|
||||
storage_options: Option<HashMap<String, String>>,
|
||||
location: Option<String>,
|
||||
namespace_client: Option<Py<PyAny>>,
|
||||
initial_bases: Option<Bound<'_, PyAny>>,
|
||||
allow_external_blob_outside_bases: bool,
|
||||
) -> PyResult<Bound<'a, PyAny>> {
|
||||
let inner = self_.get_inner()?.clone();
|
||||
let py = self_.py();
|
||||
|
||||
let mode = Self::parse_create_mode_str(mode)?;
|
||||
let initial_bases = parse_initial_bases(initial_bases)?;
|
||||
|
||||
let batches: Box<dyn arrow::array::RecordBatchReader + Send> =
|
||||
Box::new(ArrowArrayStreamReader::from_pyarrow_bound(&data)?);
|
||||
@@ -333,6 +470,12 @@ impl Connection {
|
||||
let ns_path = namespace_path.clone().unwrap_or_default();
|
||||
let mut builder = inner.create_table(name.clone(), batches).mode(mode);
|
||||
|
||||
if let Some(bases) = initial_bases {
|
||||
builder = builder.initial_bases(bases);
|
||||
}
|
||||
if allow_external_blob_outside_bases {
|
||||
builder = builder.allow_external_blob_outside_bases(true);
|
||||
}
|
||||
builder = builder.namespace(ns_path.clone());
|
||||
if let Some(storage_options) = storage_options {
|
||||
builder = builder.storage_options(storage_options);
|
||||
@@ -359,7 +502,7 @@ impl Connection {
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
#[pyo3(signature = (name, mode, schema, namespace_path=None, storage_options=None, location=None, namespace_client=None))]
|
||||
#[pyo3(signature = (name, mode, schema, namespace_path=None, storage_options=None, location=None, namespace_client=None, initial_bases=None))]
|
||||
pub fn create_empty_table<'a>(
|
||||
self_: PyRef<'a, Self>,
|
||||
name: String,
|
||||
@@ -369,11 +512,13 @@ impl Connection {
|
||||
storage_options: Option<HashMap<String, String>>,
|
||||
location: Option<String>,
|
||||
namespace_client: Option<Py<PyAny>>,
|
||||
initial_bases: Option<Bound<'_, PyAny>>,
|
||||
) -> PyResult<Bound<'a, PyAny>> {
|
||||
let inner = self_.get_inner()?.clone();
|
||||
let py = self_.py();
|
||||
|
||||
let mode = Self::parse_create_mode_str(mode)?;
|
||||
let initial_bases = parse_initial_bases(initial_bases)?;
|
||||
|
||||
let schema = Schema::from_pyarrow_bound(&schema)?;
|
||||
|
||||
@@ -382,6 +527,9 @@ impl Connection {
|
||||
.create_empty_table(name.clone(), Arc::new(schema))
|
||||
.mode(mode);
|
||||
|
||||
if let Some(bases) = initial_bases {
|
||||
builder = builder.initial_bases(bases);
|
||||
}
|
||||
builder = builder.namespace(ns_path.clone());
|
||||
if let Some(storage_options) = storage_options {
|
||||
builder = builder.storage_options(storage_options);
|
||||
|
||||
@@ -33,6 +33,7 @@ use lancedb::query::{HasQuery, QueryBase};
|
||||
use lancedb::table::AnyQuery;
|
||||
use pyo3::Bound;
|
||||
use pyo3::IntoPyObject;
|
||||
use pyo3::Py;
|
||||
use pyo3::PyAny;
|
||||
use pyo3::PyRef;
|
||||
use pyo3::PyResult;
|
||||
@@ -65,6 +66,20 @@ fn analyze_plan_options(distributed_metrics: Option<&str>) -> PyResult<QueryExec
|
||||
Ok(options)
|
||||
}
|
||||
|
||||
fn execute_to_reader_sync<Q>(
|
||||
py: Python<'_>,
|
||||
query: Q,
|
||||
max_batch_length: Option<u32>,
|
||||
timeout: Option<Duration>,
|
||||
) -> PyResult<Py<PyAny>>
|
||||
where
|
||||
Q: ExecutableQuery + Send + 'static,
|
||||
{
|
||||
let reader =
|
||||
py.detach(move || crate::arrow::execute_to_reader_sync(query, max_batch_length, timeout))?;
|
||||
Python::attach(|py| reader.into_pyarrow(py).map(|obj| obj.unbind()))
|
||||
}
|
||||
|
||||
impl<'a, 'py> FromPyObject<'a, 'py> for PyLanceDB<FtsQuery> {
|
||||
type Error = PyErr;
|
||||
|
||||
@@ -357,6 +372,7 @@ pub struct PyQueryRequest {
|
||||
pub offset: Option<usize>,
|
||||
pub take_offsets: Option<Vec<u64>>,
|
||||
pub take_row_ids: Option<Vec<u64>>,
|
||||
pub preserve_order: Option<bool>,
|
||||
pub filter: Option<PyQueryFilter>,
|
||||
pub full_text_search: Option<PyLanceDB<FtsQuery>>,
|
||||
pub select: PySelect,
|
||||
@@ -390,6 +406,7 @@ impl From<AnyQuery> for PyQueryRequest {
|
||||
offset: query_request.offset,
|
||||
take_offsets: query_request.take_offsets,
|
||||
take_row_ids: query_request.take_row_ids,
|
||||
preserve_order: query_request.preserve_order.then_some(true),
|
||||
filter: query_request.filter.map(PyQueryFilter),
|
||||
full_text_search: query_request
|
||||
.full_text_search
|
||||
@@ -423,6 +440,7 @@ impl From<AnyQuery> for PyQueryRequest {
|
||||
offset: vector_query.base.offset,
|
||||
take_offsets: vector_query.base.take_offsets,
|
||||
take_row_ids: vector_query.base.take_row_ids,
|
||||
preserve_order: vector_query.base.preserve_order.then_some(true),
|
||||
filter: vector_query.base.filter.map(PyQueryFilter),
|
||||
full_text_search: None,
|
||||
select_source_columns: PySelect::source_columns(&vector_query.base.select),
|
||||
@@ -710,6 +728,15 @@ impl Query {
|
||||
crate::arrow::execute_to_reader(self_.py(), self_.inner.clone(), max_batch_length, timeout)
|
||||
}
|
||||
|
||||
#[pyo3(signature = (max_batch_length=None, timeout=None))]
|
||||
pub fn execute_to_reader_sync(
|
||||
self_: PyRef<'_, Self>,
|
||||
max_batch_length: Option<u32>,
|
||||
timeout: Option<Duration>,
|
||||
) -> PyResult<Py<PyAny>> {
|
||||
execute_to_reader_sync(self_.py(), self_.inner.clone(), max_batch_length, timeout)
|
||||
}
|
||||
|
||||
pub fn explain_plan(self_: PyRef<'_, Self>, verbose: bool) -> PyResult<Bound<'_, PyAny>> {
|
||||
let inner = self_.inner.clone();
|
||||
future_into_py(self_.py(), async move {
|
||||
@@ -765,6 +792,10 @@ impl TakeQuery {
|
||||
self.inner = self.inner.clone().with_row_id();
|
||||
}
|
||||
|
||||
pub fn preserve_order(&mut self) {
|
||||
self.inner = self.inner.clone().preserve_order();
|
||||
}
|
||||
|
||||
pub fn use_rte(&mut self, enable: bool) {
|
||||
self.inner = self.inner.clone().use_rte(enable);
|
||||
}
|
||||
@@ -959,6 +990,23 @@ impl FTSQuery {
|
||||
)
|
||||
}
|
||||
|
||||
#[pyo3(signature = (max_batch_length=None, timeout=None))]
|
||||
pub fn execute_to_reader_sync(
|
||||
self_: PyRef<'_, Self>,
|
||||
max_batch_length: Option<u32>,
|
||||
timeout: Option<Duration>,
|
||||
) -> PyResult<Py<PyAny>> {
|
||||
execute_to_reader_sync(
|
||||
self_.py(),
|
||||
self_
|
||||
.inner
|
||||
.clone()
|
||||
.full_text_search(self_.fts_query.clone()),
|
||||
max_batch_length,
|
||||
timeout,
|
||||
)
|
||||
}
|
||||
|
||||
pub fn count_rows(self_: PyRef<'_, Self>) -> PyResult<Bound<'_, PyAny>> {
|
||||
let mut inner = self_
|
||||
.inner
|
||||
@@ -1212,6 +1260,15 @@ impl VectorQuery {
|
||||
crate::arrow::execute_to_reader(self_.py(), self_.inner.clone(), max_batch_length, timeout)
|
||||
}
|
||||
|
||||
#[pyo3(signature = (max_batch_length=None, timeout=None))]
|
||||
pub fn execute_to_reader_sync(
|
||||
self_: PyRef<'_, Self>,
|
||||
max_batch_length: Option<u32>,
|
||||
timeout: Option<Duration>,
|
||||
) -> PyResult<Py<PyAny>> {
|
||||
execute_to_reader_sync(self_.py(), self_.inner.clone(), max_batch_length, timeout)
|
||||
}
|
||||
|
||||
pub fn explain_plan(self_: PyRef<'_, Self>, verbose: bool) -> PyResult<Bound<'_, PyAny>> {
|
||||
let inner = self_.inner.clone();
|
||||
future_into_py(self_.py(), async move {
|
||||
|
||||
+199
-1
@@ -93,15 +93,19 @@
|
||||
//! `Arc` clone from becoming the final owner that drops it.
|
||||
|
||||
use std::future::Future;
|
||||
use std::panic::{AssertUnwindSafe, catch_unwind};
|
||||
use std::pin::Pin;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering};
|
||||
use std::sync::mpsc::{self, RecvTimeoutError};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use arc_swap::ArcSwapOption;
|
||||
use pyo3::{Bound, PyAny, PyResult, Python, conversion::IntoPyObject};
|
||||
use futures::FutureExt;
|
||||
use pyo3::{Bound, PyAny, PyResult, Python, conversion::IntoPyObject, exceptions::PyRuntimeError};
|
||||
use pyo3_async_runtimes::{
|
||||
TaskLocals,
|
||||
err::RustPanic,
|
||||
generic::{ContextExt, JoinError, Runtime},
|
||||
};
|
||||
use tokio::{runtime, task};
|
||||
@@ -282,6 +286,111 @@ pub fn block_on<F: std::future::Future>(fut: F) -> F::Output {
|
||||
get_runtime().block_on(fut)
|
||||
}
|
||||
|
||||
/// How often an interruptible wait returns to the Python caller for signal checks.
|
||||
const SIGNAL_CHECK_INTERVAL: Duration = Duration::from_millis(25);
|
||||
|
||||
/// Block on `fut` while keeping the Python caller responsive to signals.
|
||||
///
|
||||
/// The query task lives on the shared runtime and carries an [`OutstandingGuard`].
|
||||
/// The caller waits on the result channel without holding the GIL and periodically
|
||||
/// reacquires it to run CPython's signal handlers on the same thread. A signal
|
||||
/// exception aborts the task and drops the result receiver.
|
||||
///
|
||||
/// A synchronous callback already running on a multi-threaded Tokio worker uses
|
||||
/// [`tokio::task::block_in_place`] so the core can be handed off while the callback
|
||||
/// waits. Current-thread runtimes and contexts that reject blocking are returned as
|
||||
/// Python errors instead of falling back to the Python event loop.
|
||||
pub fn block_on_interruptible<F, T>(fut: F) -> PyResult<T>
|
||||
where
|
||||
F: Future<Output = PyResult<T>> + Send + 'static,
|
||||
T: Send + 'static,
|
||||
{
|
||||
block_on_interruptible_with(fut, || Python::attach(|py| py.check_signals()))
|
||||
}
|
||||
|
||||
fn block_on_interruptible_with<F, T, C>(fut: F, check: C) -> PyResult<T>
|
||||
where
|
||||
F: Future<Output = PyResult<T>> + Send + 'static,
|
||||
T: Send + 'static,
|
||||
C: FnMut() -> PyResult<()>,
|
||||
{
|
||||
match runtime::Handle::try_current() {
|
||||
Ok(handle) => match handle.runtime_flavor() {
|
||||
runtime::RuntimeFlavor::MultiThread => {
|
||||
let result = catch_unwind(AssertUnwindSafe(|| {
|
||||
task::block_in_place(|| block_on_interruptible_inner(fut, check))
|
||||
}));
|
||||
match result {
|
||||
Ok(result) => result,
|
||||
Err(payload) => Err(PyRuntimeError::new_err(format!(
|
||||
"synchronous query cannot block in this Tokio context: {}",
|
||||
panic_message(payload.as_ref())
|
||||
))),
|
||||
}
|
||||
}
|
||||
_ => Err(PyRuntimeError::new_err(
|
||||
"synchronous query execution cannot block on a current-thread Tokio runtime; use the async API",
|
||||
)),
|
||||
},
|
||||
Err(_) => block_on_interruptible_inner(fut, check),
|
||||
}
|
||||
}
|
||||
|
||||
fn block_on_interruptible_inner<F, T, C>(fut: F, mut check: C) -> PyResult<T>
|
||||
where
|
||||
F: Future<Output = PyResult<T>> + Send + 'static,
|
||||
T: Send + 'static,
|
||||
C: FnMut() -> PyResult<()>,
|
||||
{
|
||||
let guard = OutstandingGuard::new();
|
||||
let (tx, rx) = mpsc::sync_channel(1);
|
||||
let task = async move {
|
||||
let _guard = guard;
|
||||
let result = AssertUnwindSafe(fut).catch_unwind().await;
|
||||
// Dropping a completed result is enough when the caller has already
|
||||
// returned on an interrupt; the task's guard is dropped with it.
|
||||
let _ = tx.send(result);
|
||||
};
|
||||
let handle = get_runtime().spawn(task);
|
||||
|
||||
loop {
|
||||
match rx.recv_timeout(SIGNAL_CHECK_INTERVAL) {
|
||||
Ok(Ok(result)) => {
|
||||
check()?;
|
||||
return result;
|
||||
}
|
||||
Ok(Err(payload)) => {
|
||||
check()?;
|
||||
return Err(RustPanic::new_err(format!(
|
||||
"rust future panicked: {}",
|
||||
panic_message(payload.as_ref())
|
||||
)));
|
||||
}
|
||||
Err(RecvTimeoutError::Timeout) => {
|
||||
if let Err(error) = check() {
|
||||
handle.abort();
|
||||
return Err(error);
|
||||
}
|
||||
}
|
||||
Err(RecvTimeoutError::Disconnected) => {
|
||||
return Err(PyRuntimeError::new_err(
|
||||
"query task stopped before producing a result",
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn panic_message(payload: &(dyn std::any::Any + Send)) -> &str {
|
||||
if let Some(message) = payload.downcast_ref::<&str>() {
|
||||
message
|
||||
} else if let Some(message) = payload.downcast_ref::<String>() {
|
||||
message.as_str()
|
||||
} else {
|
||||
"unknown error"
|
||||
}
|
||||
}
|
||||
|
||||
/// Run a detached task, including when the caller is already on a runtime worker.
|
||||
/// Keep it visible to [`shutdown`] until it finishes.
|
||||
pub fn spawn_background<F>(fut: F)
|
||||
@@ -571,6 +680,95 @@ mod tests {
|
||||
shutdown(Duration::from_secs(5));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_block_on_interruptible_aborts_and_drops_future() {
|
||||
use std::sync::mpsc;
|
||||
|
||||
Python::initialize();
|
||||
let _lock = lock_runtime_state_for_test();
|
||||
let (started_tx, started_rx) = mpsc::channel();
|
||||
let (dropped_tx, dropped_rx) = mpsc::channel();
|
||||
|
||||
struct DropNotify(Option<mpsc::Sender<()>>);
|
||||
impl Drop for DropNotify {
|
||||
fn drop(&mut self) {
|
||||
if let Some(tx) = self.0.take() {
|
||||
let _ = tx.send(());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let fut = async move {
|
||||
started_tx.send(()).unwrap();
|
||||
let _notify = DropNotify(Some(dropped_tx));
|
||||
std::future::pending::<()>().await;
|
||||
#[allow(unreachable_code)]
|
||||
Ok::<(), pyo3::PyErr>(())
|
||||
};
|
||||
let result = block_on_interruptible_with(fut, || {
|
||||
Err(pyo3::exceptions::PyRuntimeError::new_err("interrupted"))
|
||||
});
|
||||
|
||||
assert!(result.is_err());
|
||||
started_rx
|
||||
.recv_timeout(Duration::from_secs(2))
|
||||
.expect("query task never started");
|
||||
dropped_rx
|
||||
.recv_timeout(Duration::from_secs(2))
|
||||
.expect("interrupted query future was not dropped");
|
||||
shutdown(Duration::from_secs(5));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_block_on_interruptible_maps_panic() {
|
||||
Python::initialize();
|
||||
let result = block_on_interruptible(async {
|
||||
panic!("boom");
|
||||
#[allow(unreachable_code)]
|
||||
Ok::<(), pyo3::PyErr>(())
|
||||
});
|
||||
assert!(
|
||||
result
|
||||
.expect_err("panic must become a Python exception")
|
||||
.to_string()
|
||||
.contains("rust future panicked: boom")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_block_on_interruptible_rejects_current_thread_runtime() {
|
||||
Python::initialize();
|
||||
let runtime = runtime::Builder::new_current_thread()
|
||||
.enable_all()
|
||||
.build()
|
||||
.expect("current-thread runtime");
|
||||
let error = runtime
|
||||
.block_on(async { block_on_interruptible(async { Ok::<_, pyo3::PyErr>(1) }) })
|
||||
.expect_err("current-thread runtime must be rejected");
|
||||
assert!(error.to_string().contains("current-thread"));
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
#[test]
|
||||
fn test_block_on_interruptible_from_single_worker_runtime() {
|
||||
Python::initialize();
|
||||
let _lock = lock_runtime_state_for_test();
|
||||
let _worker_threads = TestWorkerThreads::new(1);
|
||||
shutdown(Duration::from_secs(5));
|
||||
|
||||
let (done_tx, done_rx) = mpsc::channel();
|
||||
drop(get_runtime().spawn(async move {
|
||||
let result = block_on_interruptible(async { Ok::<_, pyo3::PyErr>(42) });
|
||||
let _ = done_tx.send(result.map_err(|error| error.to_string()));
|
||||
}));
|
||||
|
||||
let result = done_rx
|
||||
.recv_timeout(Duration::from_secs(10))
|
||||
.expect("single-worker runtime made no progress");
|
||||
assert_eq!(result.expect("single-worker query failed"), 42);
|
||||
shutdown(Duration::from_secs(5));
|
||||
}
|
||||
|
||||
// Adapted from the concurrent reproducer that found the original bug:
|
||||
// many threads hammering the runtime while shutdown races them, not
|
||||
// just the sequential rebuild path above. Before every reader held its
|
||||
|
||||
+24
-2
@@ -9,7 +9,7 @@ use std::{
|
||||
},
|
||||
};
|
||||
|
||||
use crate::runtime::{block_on, future_into_py, spawn_background};
|
||||
use crate::runtime::{block_on, block_on_interruptible, future_into_py, spawn_background};
|
||||
use crate::{
|
||||
connection::Connection,
|
||||
error::PythonErrorExt,
|
||||
@@ -1619,6 +1619,14 @@ impl Table {
|
||||
})
|
||||
}
|
||||
|
||||
pub fn schema_sync(self_: PyRef<'_, Self>) -> PyResult<Py<PyAny>> {
|
||||
let inner = self_.inner_ref()?.clone();
|
||||
let schema = self_.py().detach(move || {
|
||||
block_on_interruptible(async move { inner.schema().await.infer_error() })
|
||||
})?;
|
||||
Python::attach(|py| schema.to_pyarrow(py).map(|obj| obj.unbind()))
|
||||
}
|
||||
|
||||
#[pyo3(signature = (data, mode, progress=None, write_parallelism=None, allow_external_blob_outside_bases=false, retries=None))]
|
||||
pub fn add<'a>(
|
||||
self_: PyRef<'a, Self>,
|
||||
@@ -2240,15 +2248,29 @@ impl Table {
|
||||
}
|
||||
|
||||
/// Open lazy blob handles for `row_ids` from blob v2 column `column`.
|
||||
#[pyo3(signature = (column, row_ids, buffer_size=None))]
|
||||
#[pyo3(signature = (column, row_ids, buffer_size=None, *, version=None, snapshot_identity=None))]
|
||||
pub fn fetch_blob_files(
|
||||
self_: PyRef<'_, Self>,
|
||||
column: String,
|
||||
row_ids: Vec<u64>,
|
||||
buffer_size: Option<usize>,
|
||||
version: Option<u64>,
|
||||
snapshot_identity: Option<String>,
|
||||
) -> PyResult<Bound<'_, PyAny>> {
|
||||
let inner = self_.inner_ref()?.clone();
|
||||
future_into_py(self_.py(), async move {
|
||||
let inner = match (version, snapshot_identity) {
|
||||
(None, None) => inner,
|
||||
(Some(version), Some(identity)) => inner
|
||||
.query_snapshot_with_identity(version, &identity)
|
||||
.await
|
||||
.infer_error()?,
|
||||
_ => {
|
||||
return Err(PyValueError::new_err(
|
||||
"deferred blob reads require both query version and snapshot identity",
|
||||
));
|
||||
}
|
||||
};
|
||||
let handles = inner
|
||||
.fetch_blob_files(column.as_str(), &row_ids)
|
||||
.await
|
||||
|
||||
@@ -656,7 +656,9 @@ fn missing_blob_row_ids_error(column: &str, requested: usize, missing: &[u64]) -
|
||||
Error::InvalidInput {
|
||||
message: format!(
|
||||
"blob read for column '{column}' requested {requested} row ids but some \
|
||||
do not exist in the table{detail}; pass row ids collected from this table"
|
||||
do not exist in the table{detail}; pass row ids collected from this table. \
|
||||
If these were row positions, call take_offsets(offsets, with_row_id=True) \
|
||||
first and pass the resulting row ids"
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,6 +3,8 @@
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use lance::dataset::WriteParams;
|
||||
use lance::table::format::BasePath;
|
||||
use lance_io::object_store::StorageOptionsProvider;
|
||||
|
||||
use crate::{
|
||||
@@ -53,6 +55,67 @@ impl CreateTableBuilder {
|
||||
self
|
||||
}
|
||||
|
||||
/// Register additional base paths in the new table's manifest.
|
||||
///
|
||||
/// The bases are written in the same commit that creates the table, so a
|
||||
/// create with data stays a single atomic operation. Blob URIs that fall
|
||||
/// under a registered base are stored relative to it instead of as absolute
|
||||
/// URIs; see [`Table::fetch_blobs`].
|
||||
///
|
||||
/// Set [`BasePath::id`] to `0` to let Lance assign an ID, or to a unique
|
||||
/// non-zero value. Pass an empty list to leave the request unchanged.
|
||||
///
|
||||
/// When supplying IDs for multiple bases, use distinct explicit non-zero
|
||||
/// IDs. The pinned Lance release can collide when one base asks for
|
||||
/// automatic allocation (`0`) and another supplies an explicit ID: the
|
||||
/// create fails, the table name can remain listed but unopenable, and
|
||||
/// retrying with distinct explicit IDs succeeds. Automatic allocation for
|
||||
/// every base is supported.
|
||||
///
|
||||
/// LanceDB Embedded only.
|
||||
///
|
||||
/// [`Table::fetch_blobs`]: crate::table::Table::fetch_blobs
|
||||
pub fn initial_bases(mut self, bases: Vec<BasePath>) -> Self {
|
||||
let empty = bases.is_empty();
|
||||
self.update_lance_write_params(!empty, |params| {
|
||||
params.initial_bases = (!empty).then_some(bases);
|
||||
});
|
||||
self
|
||||
}
|
||||
|
||||
/// Store blob URIs that sit outside registered blob bases.
|
||||
///
|
||||
/// The row keeps a reference, so the object has to stay readable.
|
||||
/// [`Table::fetch_blobs`] reads from that location. Defaults to `false`.
|
||||
///
|
||||
/// The opt-in covers only the rows written by this create. A later `add`
|
||||
/// must enable it again.
|
||||
///
|
||||
/// LanceDB Embedded only.
|
||||
///
|
||||
/// [`Table::fetch_blobs`]: crate::table::Table::fetch_blobs
|
||||
pub fn allow_external_blob_outside_bases(mut self, allow: bool) -> Self {
|
||||
self.update_lance_write_params(allow, |params| {
|
||||
params.allow_external_blob_outside_bases = allow;
|
||||
});
|
||||
self
|
||||
}
|
||||
|
||||
/// Apply `update` to the Lance write parameters, creating them only when
|
||||
/// `create` is set. A no-op call on a request that has no write parameters
|
||||
/// leaves it that way, so default creation does not look customized.
|
||||
fn update_lance_write_params(&mut self, create: bool, update: impl FnOnce(&mut WriteParams)) {
|
||||
if !create && self.request.write_options.lance_write_params.is_none() {
|
||||
return;
|
||||
}
|
||||
update(
|
||||
self.request
|
||||
.write_options
|
||||
.lance_write_params
|
||||
.get_or_insert_default(),
|
||||
);
|
||||
}
|
||||
|
||||
/// Set an option for the storage layer.
|
||||
///
|
||||
/// Options already set on the connection will be inherited by the table,
|
||||
@@ -218,6 +281,24 @@ mod tests {
|
||||
assert_eq!(table.count_rows(None).await.unwrap(), 3);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn create_table_with_default_blob_base_options() {
|
||||
// Explicit empty bases and opt-out follow the ordinary create path: no
|
||||
// write parameters are attached just because the fluent methods ran.
|
||||
let db = connect("memory://").execute().await.unwrap();
|
||||
let batch = record_batch!(("id", Int64, [1, 2, 3])).unwrap();
|
||||
|
||||
let table = db
|
||||
.create_table("no_bases", batch)
|
||||
.initial_bases(Vec::new())
|
||||
.allow_external_blob_outside_bases(false)
|
||||
.execute()
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(table.count_rows(None).await.unwrap(), 3);
|
||||
}
|
||||
|
||||
async fn test_create_table_with_data<T>(data: T)
|
||||
where
|
||||
T: Scannable + 'static,
|
||||
|
||||
@@ -22,7 +22,7 @@ use crate::blob::ensure_blob_storage_version;
|
||||
use crate::connection::ConnectRequest;
|
||||
use crate::database::ReadConsistency;
|
||||
use crate::database::namespace::LanceNamespaceDatabase;
|
||||
use crate::error::{CreateDirSnafu, Error, Result};
|
||||
use crate::error::{BoxError, CreateDirSnafu, Error, Result, TableNotFoundHint};
|
||||
use crate::io::object_store::MirroringObjectStoreWrapper;
|
||||
use crate::table::NativeTable;
|
||||
use crate::utils::validate_table_name;
|
||||
@@ -698,6 +698,22 @@ impl ListingDatabase {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Explain a miss caused by connecting to a Lance dataset as if it were a
|
||||
/// database directory. The connection URI is enough to name the parent and
|
||||
/// table stem, so this needs no storage probe.
|
||||
fn lance_dataset_path_hint(&self) -> Option<String> {
|
||||
let uri = self.uri.trim_end_matches(['/', '\\']);
|
||||
let (parent, file_name) = uri.rsplit_once(['/', '\\'])?;
|
||||
let stem = file_name.strip_suffix(".lance")?;
|
||||
if stem.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let parent = if parent.is_empty() { "." } else { parent };
|
||||
Some(format!(
|
||||
". The connection URI ends with '.lance', which points to a Lance dataset rather than a database directory. Connect to the parent directory '{parent}' and open table '{stem}' instead."
|
||||
))
|
||||
}
|
||||
|
||||
/// Get the URI of a table in the database.
|
||||
fn table_uri(&self, name: &str) -> Result<String> {
|
||||
validate_table_name(name)?;
|
||||
@@ -1180,6 +1196,7 @@ impl Database for ListingDatabase {
|
||||
if !request.namespace_path.is_empty() {
|
||||
return self.namespace_database().open_table(request).await;
|
||||
}
|
||||
let derived_location = request.location.is_none();
|
||||
// Use provided location if available, otherwise derive from table name
|
||||
let table_uri = match request.location.clone() {
|
||||
Some(location) => location,
|
||||
@@ -1233,20 +1250,29 @@ impl Database for ListingDatabase {
|
||||
});
|
||||
read_params.session(self.session.clone());
|
||||
|
||||
let native_table = Arc::new(
|
||||
NativeTable::open_with_params(
|
||||
&table_uri,
|
||||
&request.name,
|
||||
request.namespace_path,
|
||||
self.store_wrapper.clone(),
|
||||
Some(read_params),
|
||||
self.read_consistency_interval,
|
||||
request.namespace_client,
|
||||
HashSet::new(), // listing database doesn't support server-side queries
|
||||
request.managed_versioning, // Pass through managed_versioning from request
|
||||
)
|
||||
.await?,
|
||||
);
|
||||
let native_table = match NativeTable::open_with_params(
|
||||
&table_uri,
|
||||
&request.name,
|
||||
request.namespace_path,
|
||||
self.store_wrapper.clone(),
|
||||
Some(read_params),
|
||||
self.read_consistency_interval,
|
||||
request.namespace_client,
|
||||
HashSet::new(), // listing database doesn't support server-side queries
|
||||
request.managed_versioning, // Pass through managed_versioning from request
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(table) => Arc::new(table),
|
||||
Err(Error::TableNotFound { name, source }) if derived_location => {
|
||||
let source: BoxError = match self.lance_dataset_path_hint() {
|
||||
Some(hint) => Box::new(TableNotFoundHint::new(hint, source)),
|
||||
None => source,
|
||||
};
|
||||
return Err(Error::TableNotFound { name, source });
|
||||
}
|
||||
Err(error) => return Err(error),
|
||||
};
|
||||
Ok(native_table)
|
||||
}
|
||||
|
||||
@@ -1843,10 +1869,100 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
async fn setup_database() -> (tempfile::TempDir, ListingDatabase) {
|
||||
/// A connection made to a dataset path cannot also be a database directory. The
|
||||
/// miss names the parent and table stem so the caller can fix the connection.
|
||||
#[tokio::test]
|
||||
async fn test_open_table_dataset_path_hint() {
|
||||
let tempdir = tempdir().unwrap();
|
||||
let uri = tempdir.path().to_str().unwrap();
|
||||
let data_dir = tempdir.path().join("data");
|
||||
let data_db = setup_database_at(data_dir.to_str().unwrap()).await;
|
||||
create_tables(&data_db, &["embeddings"]).await;
|
||||
|
||||
let dataset_path = data_dir.join("embeddings.lance");
|
||||
let dataset_db = setup_database_at(dataset_path.to_str().unwrap()).await;
|
||||
let error = dataset_db
|
||||
.open_table(OpenTableRequest {
|
||||
name: "embeddings".to_string(),
|
||||
namespace_path: vec![],
|
||||
index_cache_size: None,
|
||||
lance_read_params: None,
|
||||
location: None,
|
||||
namespace_client: None,
|
||||
managed_versioning: None,
|
||||
})
|
||||
.await
|
||||
.unwrap_err();
|
||||
|
||||
assert!(
|
||||
matches!(&error, Error::TableNotFound { name, .. } if name == "embeddings"),
|
||||
"the dataset path miss changed classification: {error:?}"
|
||||
);
|
||||
let message = error.to_string();
|
||||
assert!(
|
||||
message.contains("points to a Lance dataset rather than a database directory"),
|
||||
"the hint did not explain the dataset path: {message}"
|
||||
);
|
||||
assert!(
|
||||
message.contains(&format!("parent directory '{}'", data_dir.display())),
|
||||
"the hint did not name the parent directory: {message}"
|
||||
);
|
||||
assert!(
|
||||
message.contains("open table 'embeddings' instead"),
|
||||
"the hint did not name the table stem: {message}"
|
||||
);
|
||||
}
|
||||
|
||||
/// The hint belongs only to a derived URI. An explicit location is the caller's
|
||||
/// own choice, so a miss there keeps the original message.
|
||||
#[tokio::test]
|
||||
async fn test_open_table_explicit_location_skips_dataset_path_hint() {
|
||||
let tempdir = tempdir().unwrap();
|
||||
let data_dir = tempdir.path().join("data");
|
||||
let data_db = setup_database_at(data_dir.to_str().unwrap()).await;
|
||||
create_tables(&data_db, &["embeddings"]).await;
|
||||
let dataset_path = data_dir.join("embeddings.lance");
|
||||
let dataset_db = setup_database_at(dataset_path.to_str().unwrap()).await;
|
||||
|
||||
let table = dataset_db
|
||||
.open_table(OpenTableRequest {
|
||||
name: "alias".to_string(),
|
||||
namespace_path: vec![],
|
||||
index_cache_size: None,
|
||||
lance_read_params: None,
|
||||
location: Some(dataset_path.to_str().unwrap().to_string()),
|
||||
namespace_client: None,
|
||||
managed_versioning: None,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(table.count_rows(None).await.unwrap(), 0);
|
||||
|
||||
let missing_path = tempdir.path().join("missing.lance");
|
||||
let error = dataset_db
|
||||
.open_table(OpenTableRequest {
|
||||
name: "missing".to_string(),
|
||||
namespace_path: vec![],
|
||||
index_cache_size: None,
|
||||
lance_read_params: None,
|
||||
location: Some(missing_path.to_str().unwrap().to_string()),
|
||||
namespace_client: None,
|
||||
managed_versioning: None,
|
||||
})
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(
|
||||
matches!(&error, Error::TableNotFound { name, .. } if name == "missing"),
|
||||
"the explicit location miss changed classification: {error:?}"
|
||||
);
|
||||
assert!(
|
||||
!error
|
||||
.to_string()
|
||||
.contains("points to a Lance dataset rather than a database directory"),
|
||||
"an explicit location still received the connection hint: {error}"
|
||||
);
|
||||
}
|
||||
|
||||
async fn setup_database_at(uri: &str) -> ListingDatabase {
|
||||
let request = ConnectRequest {
|
||||
uri: uri.to_string(),
|
||||
#[cfg(feature = "remote")]
|
||||
@@ -1857,11 +1973,14 @@ mod tests {
|
||||
read_consistency_interval: None,
|
||||
session: None,
|
||||
};
|
||||
|
||||
let db = ListingDatabase::connect_with_options(&request)
|
||||
ListingDatabase::connect_with_options(&request)
|
||||
.await
|
||||
.unwrap();
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
async fn setup_database() -> (tempfile::TempDir, ListingDatabase) {
|
||||
let tempdir = tempdir().unwrap();
|
||||
let db = setup_database_at(tempdir.path().to_str().unwrap()).await;
|
||||
(tempdir, db)
|
||||
}
|
||||
|
||||
|
||||
@@ -344,6 +344,46 @@ fn server_build_suffix(_source: &(dyn std::error::Error + Send + Sync + 'static)
|
||||
String::new()
|
||||
}
|
||||
|
||||
/// Actionable guidance attached to a [`Error::TableNotFound`].
|
||||
///
|
||||
/// The hint is kept in the error source chain so the missing-table
|
||||
/// classification and the original failure stay unchanged.
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct TableNotFoundHint {
|
||||
hint: String,
|
||||
source: BoxError,
|
||||
}
|
||||
|
||||
impl TableNotFoundHint {
|
||||
pub(crate) fn new(hint: impl Into<String>, source: BoxError) -> Self {
|
||||
Self {
|
||||
hint: hint.into(),
|
||||
source,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Display for TableNotFoundHint {
|
||||
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
|
||||
f.write_str(&self.hint)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for TableNotFoundHint {
|
||||
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
|
||||
Some(self.source.as_ref())
|
||||
}
|
||||
}
|
||||
|
||||
fn table_not_found_hint<'a>(
|
||||
source: &'a (dyn std::error::Error + Send + Sync + 'static),
|
||||
) -> &'a str {
|
||||
source
|
||||
.downcast_ref::<TableNotFoundHint>()
|
||||
.map(|hint| hint.hint.as_str())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
#[derive(Debug, Snafu)]
|
||||
#[snafu(visibility(pub(crate)))]
|
||||
pub enum Error {
|
||||
@@ -351,7 +391,11 @@ pub enum Error {
|
||||
InvalidTableName { name: String, reason: String },
|
||||
#[snafu(display("Invalid input, {message}"))]
|
||||
InvalidInput { message: String },
|
||||
#[snafu(display("Table '{name}' was not found{}", server_build_suffix(source.as_ref())))]
|
||||
#[snafu(display(
|
||||
"Table '{name}' was not found{}{}",
|
||||
server_build_suffix(source.as_ref()),
|
||||
table_not_found_hint(source.as_ref())
|
||||
))]
|
||||
TableNotFound { name: String, source: BoxError },
|
||||
#[snafu(display(
|
||||
"Table '{name}' exists but could not be loaded (it may be corrupt or incomplete): {source}"
|
||||
|
||||
@@ -238,6 +238,7 @@ pub use connection::{ConnectNamespaceBuilder, Connection};
|
||||
pub use error::{Error, JobFailure, Result};
|
||||
pub use function::FunctionVersion;
|
||||
pub use job::Job;
|
||||
pub use lance::table::format::BasePath;
|
||||
use lance_index::vector::ApproxMode as LanceApproxMode;
|
||||
use lance_linalg::distance::DistanceType as LanceDistanceType;
|
||||
pub use materialized_view::{
|
||||
|
||||
+208
-10
@@ -867,6 +867,13 @@ pub struct QueryRequest {
|
||||
#[doc(hidden)]
|
||||
pub take_row_ids: Option<Vec<u64>>,
|
||||
|
||||
/// Restore `take_offsets` occurrences in the exact requested input order.
|
||||
///
|
||||
/// This is client-side execution metadata and is not sent to remote
|
||||
/// services. It cannot be combined with an explicit `order_by`.
|
||||
#[doc(hidden)]
|
||||
pub preserve_order: bool,
|
||||
|
||||
/// Apply filter to the returned rows.
|
||||
pub filter: Option<QueryFilter>,
|
||||
|
||||
@@ -937,6 +944,7 @@ impl Default for QueryRequest {
|
||||
offset: None,
|
||||
take_offsets: None,
|
||||
take_row_ids: None,
|
||||
preserve_order: false,
|
||||
filter: None,
|
||||
filter_error: None,
|
||||
full_text_search: None,
|
||||
@@ -2065,7 +2073,6 @@ impl ExecutionPlan for TakeRestoreExec {
|
||||
pub struct TakeQuery {
|
||||
parent: Arc<dyn BaseTable>,
|
||||
request: QueryRequest,
|
||||
preserve_order: bool,
|
||||
}
|
||||
|
||||
struct TakeLookup {
|
||||
@@ -2100,7 +2107,6 @@ impl TakeQuery {
|
||||
take_offsets: Some(offsets),
|
||||
..Default::default()
|
||||
},
|
||||
preserve_order: false,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2122,16 +2128,17 @@ impl TakeQuery {
|
||||
take_row_ids: Some(row_ids),
|
||||
..Default::default()
|
||||
},
|
||||
preserve_order: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Preserve the requested offset order when restoring duplicate occurrences.
|
||||
///
|
||||
/// This is reserved for readers whose API explicitly guarantees ordering.
|
||||
pub(crate) fn preserve_order(mut self) -> Self {
|
||||
/// Found rows follow the input order, including repeated offsets. Missing
|
||||
/// non-negative offsets are omitted. This cannot be combined with an
|
||||
/// explicit `order_by`.
|
||||
pub fn preserve_order(mut self) -> Self {
|
||||
debug_assert!(self.request.take_offsets.is_some());
|
||||
self.preserve_order = true;
|
||||
self.request.preserve_order = true;
|
||||
self
|
||||
}
|
||||
|
||||
@@ -2203,8 +2210,25 @@ impl TakeQuery {
|
||||
});
|
||||
}
|
||||
};
|
||||
let preserve_order =
|
||||
preserve_order || (by_row_id && request.order_by.as_ref().is_none_or(Vec::is_empty));
|
||||
// The explicit flag only applies to offset takes. Row-id takes retain
|
||||
// their existing implicit ordering behavior: input order when no sort is
|
||||
// requested, and the explicit sort otherwise.
|
||||
let explicit_preserve_order = !by_row_id && (preserve_order || request.preserve_order);
|
||||
if explicit_preserve_order
|
||||
&& request
|
||||
.order_by
|
||||
.as_ref()
|
||||
.is_some_and(|order_by| !order_by.is_empty())
|
||||
{
|
||||
return Err(Error::InvalidInput {
|
||||
message: "preserve_order cannot be combined with an explicit order_by".to_string(),
|
||||
});
|
||||
}
|
||||
let preserve_order = if by_row_id {
|
||||
request.order_by.as_ref().is_none_or(Vec::is_empty)
|
||||
} else {
|
||||
explicit_preserve_order
|
||||
};
|
||||
let (mut request, ordering_column, drop_ordering_column, output_projection) = if by_row_id {
|
||||
let mut request = request.clone();
|
||||
let with_row_id = request.with_row_id;
|
||||
@@ -2527,7 +2551,7 @@ impl ExecutableQuery for TakeQuery {
|
||||
self.parent.as_ref(),
|
||||
&self.request,
|
||||
options,
|
||||
self.preserve_order,
|
||||
self.request.preserve_order,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
@@ -2564,7 +2588,7 @@ impl ExecutableQuery for TakeQuery {
|
||||
self.parent.as_ref(),
|
||||
&self.request,
|
||||
verbose,
|
||||
self.preserve_order,
|
||||
self.request.preserve_order,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
@@ -4295,6 +4319,53 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
async fn make_preserve_order_test_table(tmp_dir: &tempfile::TempDir) -> Table {
|
||||
let dataset_path = tmp_dir.path().join("preserve_order.lance");
|
||||
let conn = connect(dataset_path.to_str().unwrap())
|
||||
.execute()
|
||||
.await
|
||||
.unwrap();
|
||||
let table = conn
|
||||
.create_table(
|
||||
"my_table",
|
||||
RecordBatch::try_from_iter([(
|
||||
"idx",
|
||||
Arc::new(Int32Array::from(vec![0, 1, 2, 3])) as Arc<dyn Array>,
|
||||
)])
|
||||
.unwrap(),
|
||||
)
|
||||
.execute()
|
||||
.await
|
||||
.unwrap();
|
||||
table
|
||||
.add(
|
||||
RecordBatch::try_from_iter([(
|
||||
"idx",
|
||||
Arc::new(Int32Array::from(vec![4, 5, 6, 7])) as Arc<dyn Array>,
|
||||
)])
|
||||
.unwrap(),
|
||||
)
|
||||
.execute()
|
||||
.await
|
||||
.unwrap();
|
||||
table.delete("idx IN (1, 6)").await.unwrap();
|
||||
table
|
||||
}
|
||||
|
||||
fn collect_ids(batches: &[RecordBatch]) -> Vec<i32> {
|
||||
batches
|
||||
.iter()
|
||||
.flat_map(|batch| {
|
||||
batch
|
||||
.column_by_name("idx")
|
||||
.unwrap()
|
||||
.as_primitive::<Int32Type>()
|
||||
.values()
|
||||
.to_vec()
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_take_offsets_applies_pagination_after_restoration() {
|
||||
let tmp_dir = tempdir().unwrap();
|
||||
@@ -4345,6 +4416,104 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_take_offsets_preserve_order_across_fragments_deletes_and_batches() {
|
||||
let tmp_dir = tempdir().unwrap();
|
||||
let table = make_preserve_order_test_table(&tmp_dir).await;
|
||||
let offsets = vec![5, 0, 5, 2, 99, 4, 0];
|
||||
let expected = vec![7, 0, 7, 3, 5, 0];
|
||||
|
||||
let batches = table
|
||||
.take_offsets(offsets.clone())
|
||||
.preserve_order()
|
||||
.select(Select::Columns(vec!["idx".to_string()]))
|
||||
.execute_with_options(QueryExecutionOptions {
|
||||
max_batch_length: 1,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap()
|
||||
.try_collect::<Vec<_>>()
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert!(batches.iter().all(|batch| batch.num_rows() <= 1));
|
||||
assert_eq!(collect_ids(&batches), expected);
|
||||
|
||||
let converted = table
|
||||
.take_offsets(offsets)
|
||||
.preserve_order()
|
||||
.select(Select::Columns(vec!["idx".to_string()]))
|
||||
.into_request();
|
||||
let batches = table
|
||||
.base_table()
|
||||
.query(
|
||||
&AnyQuery::Query(converted),
|
||||
QueryExecutionOptions::default(),
|
||||
)
|
||||
.await
|
||||
.unwrap()
|
||||
.try_collect::<Vec<_>>()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(collect_ids(&batches), expected);
|
||||
|
||||
let batches = table
|
||||
.take_offsets(vec![])
|
||||
.preserve_order()
|
||||
.select(Select::Columns(vec!["idx".to_string()]))
|
||||
.execute()
|
||||
.await
|
||||
.unwrap()
|
||||
.try_collect::<Vec<_>>()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(batches.iter().map(RecordBatch::num_rows).sum::<usize>(), 0);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_take_offsets_preserve_order_paginates_after_restoration() {
|
||||
let tmp_dir = tempdir().unwrap();
|
||||
let table = make_preserve_order_test_table(&tmp_dir).await;
|
||||
|
||||
let batches = table
|
||||
.take_offsets(vec![5, 0, 5, 2, 4, 0])
|
||||
.preserve_order()
|
||||
.select(Select::Columns(vec!["idx".to_string()]))
|
||||
.offset(2)
|
||||
.limit(4)
|
||||
.execute()
|
||||
.await
|
||||
.unwrap()
|
||||
.try_collect::<Vec<_>>()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(collect_ids(&batches), vec![7, 3, 5, 0]);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_take_offsets_preserve_order_rejects_order_by() {
|
||||
let tmp_dir = tempdir().unwrap();
|
||||
let table = make_preserve_order_test_table(&tmp_dir).await;
|
||||
|
||||
let error = table
|
||||
.take_offsets(vec![0, 2])
|
||||
.preserve_order()
|
||||
.order_by(Some(vec![ColumnOrdering::asc_nulls_first(
|
||||
"idx".to_string(),
|
||||
)]))
|
||||
.execute()
|
||||
.await
|
||||
.err()
|
||||
.unwrap();
|
||||
assert!(
|
||||
error
|
||||
.to_string()
|
||||
.contains("preserve_order cannot be combined with an explicit order_by"),
|
||||
"{error}"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_take_offsets_create_plan_restores_occurrences() {
|
||||
let tmp_dir = tempdir().unwrap();
|
||||
@@ -4613,6 +4782,35 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_take_row_ids_ignores_offset_preserve_flag_with_explicit_sort() {
|
||||
let tmp_dir = tempdir().unwrap();
|
||||
let table = make_test_table(&tmp_dir).await;
|
||||
let mut request = table
|
||||
.take_row_ids(vec![17, 5, 1, 5])
|
||||
.order_by(Some(vec![ColumnOrdering::asc_nulls_first(
|
||||
"id".to_string(),
|
||||
)]))
|
||||
.offset(1)
|
||||
.limit(2)
|
||||
.into_request();
|
||||
request.preserve_order = true;
|
||||
|
||||
let batches = table
|
||||
.base_table()
|
||||
.query(&AnyQuery::Query(request), QueryExecutionOptions::default())
|
||||
.await
|
||||
.unwrap()
|
||||
.try_collect::<Vec<_>>()
|
||||
.await
|
||||
.unwrap();
|
||||
let actual = concat_batches(&batches[0].schema(), &batches).unwrap();
|
||||
assert_eq!(
|
||||
actual["id"].as_primitive::<Int32Type>().values().as_ref(),
|
||||
&[5, 5]
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_take_row_ids_explicit_order_by() {
|
||||
let tmp_dir = tempdir().unwrap();
|
||||
|
||||
@@ -1552,6 +1552,30 @@ impl<S: HttpSend> Database for RemoteDatabase<S> {
|
||||
// The remote create endpoint does not transmit Lance write parameters.
|
||||
// Reject them before consuming data or issuing a request, especially
|
||||
// for overwrite: silently using the server's format can lose intent.
|
||||
//
|
||||
// Name the blob-base options specifically: they carry data placement
|
||||
// and URI-resolution semantics the server cannot honor, and a generic
|
||||
// "write_options" message would not tell the caller which input to drop.
|
||||
if let Some(params) = request.write_options.lance_write_params.as_ref() {
|
||||
let unsupported = if params
|
||||
.initial_bases
|
||||
.as_ref()
|
||||
.is_some_and(|bases| !bases.is_empty())
|
||||
{
|
||||
Some("initial_bases")
|
||||
} else if params.allow_external_blob_outside_bases {
|
||||
Some("allow_external_blob_outside_bases")
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if let Some(option) = unsupported {
|
||||
return Err(Error::NotSupported {
|
||||
message: format!(
|
||||
"{option} is not supported for table creation in LanceDB Enterprise"
|
||||
),
|
||||
});
|
||||
}
|
||||
}
|
||||
for (option, provided) in [
|
||||
(
|
||||
"write_options (including storage_options)",
|
||||
@@ -2913,6 +2937,89 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_create_rejects_blob_base_options_before_reading_input() {
|
||||
let conn = Connection::new_with_handler(|_| -> http::Response<&'static str> {
|
||||
panic!("must not send a create request")
|
||||
});
|
||||
let schema = Arc::new(Schema::new(vec![Field::new("a", DataType::Int32, false)]));
|
||||
let base = crate::BasePath::new(1, "s3://bucket/prefix".to_string(), None, false);
|
||||
|
||||
let reads = Arc::new(AtomicUsize::new(0));
|
||||
let data: Box<dyn arrow_array::RecordBatchReader + Send> = Box::new(CountingReader {
|
||||
schema: schema.clone(),
|
||||
reads: reads.clone(),
|
||||
});
|
||||
let err = conn
|
||||
.create_table("table1", data)
|
||||
.initial_bases(vec![base])
|
||||
.execute()
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(
|
||||
matches!(err, Error::NotSupported { ref message } if message.contains("initial_bases")),
|
||||
"got {err:?}"
|
||||
);
|
||||
assert_eq!(reads.load(Ordering::SeqCst), 0);
|
||||
|
||||
let err = conn
|
||||
.create_empty_table("table1", schema)
|
||||
.allow_external_blob_outside_bases(true)
|
||||
.execute()
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(
|
||||
matches!(err, Error::NotSupported { ref message } if message.contains("allow_external_blob_outside_bases")),
|
||||
"got {err:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_create_accepts_empty_blob_base_options() {
|
||||
// Empty bases and the explicit opt-out are not customization: the remote
|
||||
// create must stay an ordinary request.
|
||||
let conn = Connection::new_with_handler(|request| {
|
||||
assert_eq!(request.url().path(), "/v1/table/table1/create/");
|
||||
http::Response::builder().status(200).body("").unwrap()
|
||||
});
|
||||
let schema = Arc::new(Schema::new(vec![Field::new("a", DataType::Int32, false)]));
|
||||
let data = RecordBatch::try_new(
|
||||
schema.clone(),
|
||||
vec![Arc::new(Int32Array::from(vec![1, 2, 3]))],
|
||||
)
|
||||
.unwrap();
|
||||
for builder in [
|
||||
conn.create_table("table1", data)
|
||||
.initial_bases(Vec::new())
|
||||
.allow_external_blob_outside_bases(false),
|
||||
conn.create_empty_table("table1", schema)
|
||||
.initial_bases(Vec::new())
|
||||
.allow_external_blob_outside_bases(false),
|
||||
] {
|
||||
assert!(builder.execute().await.is_ok());
|
||||
}
|
||||
}
|
||||
|
||||
struct CountingReader {
|
||||
schema: Arc<Schema>,
|
||||
reads: Arc<AtomicUsize>,
|
||||
}
|
||||
|
||||
impl Iterator for CountingReader {
|
||||
type Item = Result<RecordBatch, arrow_schema::ArrowError>;
|
||||
|
||||
fn next(&mut self) -> Option<Self::Item> {
|
||||
self.reads.fetch_add(1, Ordering::SeqCst);
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
impl arrow_array::RecordBatchReader for CountingReader {
|
||||
fn schema(&self) -> arrow_schema::SchemaRef {
|
||||
self.schema.clone()
|
||||
}
|
||||
}
|
||||
|
||||
#[rstest]
|
||||
#[tokio::test]
|
||||
async fn test_open_rejects_local_options_even_when_cached(#[values(false, true)] cached: bool) {
|
||||
|
||||
@@ -3420,7 +3420,8 @@ impl<S: HttpSend> BaseTable for RemoteTable<S> {
|
||||
if let AnyQuery::Query(request) = query
|
||||
&& request.has_take()
|
||||
{
|
||||
return crate::query::create_take_plan(self, request, options, false).await;
|
||||
return crate::query::create_take_plan(self, request, options, request.preserve_order)
|
||||
.await;
|
||||
}
|
||||
|
||||
let streams = self.execute_query(query, &options).await?;
|
||||
@@ -3444,8 +3445,13 @@ impl<S: HttpSend> BaseTable for RemoteTable<S> {
|
||||
if let AnyQuery::Query(request) = query
|
||||
&& request.has_take()
|
||||
{
|
||||
let plan =
|
||||
crate::query::create_take_plan(self, request, options.clone(), false).await?;
|
||||
let plan = crate::query::create_take_plan(
|
||||
self,
|
||||
request,
|
||||
options.clone(),
|
||||
request.preserve_order,
|
||||
)
|
||||
.await?;
|
||||
let inner = execute_plan(plan, Default::default())?;
|
||||
let inner = MaxBatchLengthStream::new_boxed(inner, options.max_batch_length as usize);
|
||||
let inner = if let Some(timeout) = options.timeout {
|
||||
@@ -3508,7 +3514,8 @@ impl<S: HttpSend> BaseTable for RemoteTable<S> {
|
||||
if let AnyQuery::Query(request) = query
|
||||
&& request.has_take()
|
||||
{
|
||||
return crate::query::explain_take_plan(self, request, verbose, false).await;
|
||||
return crate::query::explain_take_plan(self, request, verbose, request.preserve_order)
|
||||
.await;
|
||||
}
|
||||
|
||||
let base_request = self
|
||||
@@ -8601,8 +8608,8 @@ mod tests {
|
||||
Field::new("_rowoffset", DataType::UInt64, false),
|
||||
])),
|
||||
vec![
|
||||
Arc::new(Int32Array::from(vec![5])),
|
||||
Arc::new(arrow_array::UInt64Array::from(vec![5])),
|
||||
Arc::new(Int32Array::from(vec![1, 5])),
|
||||
Arc::new(arrow_array::UInt64Array::from(vec![1, 5])),
|
||||
],
|
||||
)
|
||||
.unwrap();
|
||||
@@ -8614,7 +8621,8 @@ mod tests {
|
||||
});
|
||||
|
||||
let request = table
|
||||
.take_offsets(vec![5, 5])
|
||||
.take_offsets(vec![5, 1, 5])
|
||||
.preserve_order()
|
||||
.select(crate::query::Select::columns(&["id"]))
|
||||
.into_request();
|
||||
let batches = table
|
||||
@@ -8626,12 +8634,24 @@ mod tests {
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(batches.iter().map(RecordBatch::num_rows).sum::<usize>(), 2);
|
||||
assert_eq!(batches.iter().map(RecordBatch::num_rows).sum::<usize>(), 3);
|
||||
assert!(
|
||||
batches
|
||||
.iter()
|
||||
.all(|batch| batch.schema().fields().len() == 1)
|
||||
);
|
||||
let ids = batches
|
||||
.iter()
|
||||
.flat_map(|batch| {
|
||||
batch
|
||||
.column_by_name("id")
|
||||
.unwrap()
|
||||
.as_primitive::<arrow_array::types::Int32Type>()
|
||||
.values()
|
||||
.to_vec()
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(ids, vec![5, 1, 5]);
|
||||
}
|
||||
|
||||
#[rstest::rstest]
|
||||
|
||||
@@ -1156,7 +1156,9 @@ impl<S: HttpSend> RemoteTable<S> {
|
||||
return Err(Error::InvalidInput {
|
||||
message: format!(
|
||||
"blob read for column '{column}' requested {} row ids but only {found} exist \
|
||||
in the table; pass row ids collected from this table",
|
||||
in the table; pass row ids collected from this table. If these were row \
|
||||
positions, call take_offsets(offsets, with_row_id=True) first and pass the \
|
||||
resulting row ids",
|
||||
unique_row_ids.len()
|
||||
),
|
||||
});
|
||||
@@ -1190,9 +1192,20 @@ impl<S: HttpSend> RemoteTable<S> {
|
||||
.client
|
||||
.post(&format!("/v1/table/{}/query/", self.identifier))
|
||||
.json(&body);
|
||||
// The query route opens the requested version and reports the identity of
|
||||
// the dataset it actually read. It does not validate the request identity,
|
||||
// so accept descriptors only after comparing the response echo.
|
||||
let request = if let Some(identity) = &self.expected_query_snapshot {
|
||||
request.header(QUERY_SNAPSHOT_HEADER, identity)
|
||||
} else {
|
||||
request
|
||||
};
|
||||
let (request_id, response) = self
|
||||
.send_with_freshness(request, true, read_snapshot.freshness)
|
||||
.await?;
|
||||
if response.status().is_success() {
|
||||
check_query_snapshot_response(self.expected_query_snapshot.as_deref(), &response)?;
|
||||
}
|
||||
let response_version = response
|
||||
.headers()
|
||||
.get(&VERSION_HEADER)
|
||||
@@ -2046,6 +2059,80 @@ mod tests {
|
||||
assert!(requests.lock().unwrap().is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn remote_blob_files_reject_unverified_descriptor_identity_before_values() {
|
||||
const EXPECTED: &str =
|
||||
"v1:bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb";
|
||||
const OTHER: &str = "v1:cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc";
|
||||
for response_identity in [None, Some(OTHER)] {
|
||||
let range_requests = Arc::new(AtomicUsize::new(0));
|
||||
let captured_ranges = range_requests.clone();
|
||||
let table = RemoteTable::new_mock(
|
||||
"my_table".to_string(),
|
||||
move |request| {
|
||||
let path = request.url().path().to_string();
|
||||
if path == "/v1/table/my_table/query/" {
|
||||
// Row 20 is NULL and row 40 is empty, so an unverified
|
||||
// result could escape without any payload request.
|
||||
assert_eq!(request.headers()[QUERY_SNAPSHOT_HEADER], EXPECTED);
|
||||
let body: serde_json::Value =
|
||||
serde_json::from_slice(request.body().unwrap().as_bytes().unwrap())
|
||||
.unwrap();
|
||||
assert_eq!(filter_row_ids(body["filter"].as_str().unwrap()), [20, 40]);
|
||||
let batch = RecordBatch::try_from_iter([
|
||||
(
|
||||
"image",
|
||||
Arc::new(descriptors(&[None, Some((BlobKind::Inline, 0))]))
|
||||
as Arc<dyn Array>,
|
||||
),
|
||||
(
|
||||
ROW_ID,
|
||||
Arc::new(UInt64Array::from_iter_values([20, 40])) as Arc<dyn Array>,
|
||||
),
|
||||
])
|
||||
.unwrap();
|
||||
let mut body = Vec::new();
|
||||
let mut writer =
|
||||
arrow_ipc::writer::FileWriter::try_new(&mut body, &batch.schema())
|
||||
.unwrap();
|
||||
writer.write(&batch).unwrap();
|
||||
writer.finish().unwrap();
|
||||
drop(writer);
|
||||
let mut response = http::Response::builder()
|
||||
.status(200)
|
||||
.header(VERSION_HEADER, "42");
|
||||
if let Some(identity) = response_identity {
|
||||
response = response.header(QUERY_SNAPSHOT_HEADER, identity);
|
||||
}
|
||||
return response.body(body).unwrap();
|
||||
}
|
||||
if path.starts_with("/v1/table/my_table/blob/") {
|
||||
captured_ranges.fetch_add(1, Ordering::SeqCst);
|
||||
panic!("descriptor verification must fail before any payload read");
|
||||
}
|
||||
panic!("unexpected path: {path}");
|
||||
},
|
||||
Some(Version::new(0, 5, 0)),
|
||||
);
|
||||
let snapshot = table
|
||||
.query_snapshot_with_identity(42, EXPECTED)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let error = snapshot
|
||||
.fetch_blob_files("image", &[20, 40])
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(
|
||||
error
|
||||
.to_string()
|
||||
.contains("did not verify the query snapshot identity"),
|
||||
"{error}"
|
||||
);
|
||||
assert_eq!(range_requests.load(Ordering::SeqCst), 0);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn remote_blob_ranges_accept_empty_requests_without_http() {
|
||||
let (table, requests) = mock_take_blob_table(vec![], Some("7"));
|
||||
|
||||
@@ -180,7 +180,8 @@ pub async fn create_plan(
|
||||
if let AnyQuery::Query(request) = &query
|
||||
&& request.has_take()
|
||||
{
|
||||
return crate::query::create_take_plan(table, request, options, false).await;
|
||||
return crate::query::create_take_plan(table, request, options, request.preserve_order)
|
||||
.await;
|
||||
}
|
||||
|
||||
let query = match query {
|
||||
|
||||
@@ -2085,3 +2085,377 @@ async fn blob_layout_rte_merge_normalizes_before_writing() -> Result<()> {
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// One-row blob v2 batch carrying an external URI with an explicit byte range.
|
||||
fn range_uri_batch(
|
||||
ids: &[i64],
|
||||
uris: &[&str],
|
||||
positions: &[Option<u64>],
|
||||
sizes: &[Option<u64>],
|
||||
) -> RecordBatch {
|
||||
let image_field = lancedb::blob("image", true);
|
||||
let DataType::Struct(children) = image_field.data_type().clone() else {
|
||||
unreachable!("blob field is a struct");
|
||||
};
|
||||
let values = StructArray::new(
|
||||
children,
|
||||
vec![
|
||||
new_null_array(&DataType::LargeBinary, ids.len()),
|
||||
Arc::new(StringArray::from_iter_values(uris.iter().copied())),
|
||||
Arc::new(UInt64Array::from(positions.to_vec())),
|
||||
Arc::new(UInt64Array::from(sizes.to_vec())),
|
||||
],
|
||||
None,
|
||||
);
|
||||
RecordBatch::try_new(
|
||||
Arc::new(Schema::new(vec![
|
||||
Field::new("id", DataType::Int64, false),
|
||||
image_field,
|
||||
])),
|
||||
vec![Arc::new(Int64Array::from(ids.to_vec())), Arc::new(values)],
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
fn wide_blob_table_schema() -> Arc<Schema> {
|
||||
Arc::new(Schema::new(vec![
|
||||
Field::new("id", DataType::Int64, false),
|
||||
lancedb::blob("image", true),
|
||||
]))
|
||||
}
|
||||
|
||||
fn local_base(id: u32, path: String) -> BasePath {
|
||||
BasePath {
|
||||
id,
|
||||
name: Some(format!("base{id}")),
|
||||
path,
|
||||
is_dataset_root: false,
|
||||
}
|
||||
}
|
||||
|
||||
fn write_local_payload(dir: &std::path::Path, name: &str, payload: &[u8]) -> (String, String) {
|
||||
let path = dir.join(name);
|
||||
std::fs::write(&path, payload).unwrap();
|
||||
(
|
||||
url::Url::from_file_path(&path).unwrap().to_string(),
|
||||
url::Url::from_directory_path(dir).unwrap().to_string(),
|
||||
)
|
||||
}
|
||||
|
||||
/// A create with data and `initial_bases` must commit once. Registering the
|
||||
/// base in a later commit, or creating empty first, would bump the version and
|
||||
/// leave an intermediate table without its storage.
|
||||
#[tokio::test]
|
||||
async fn create_table_with_data_registers_initial_base_atomically() -> Result<()> {
|
||||
let tmp = tempdir().unwrap();
|
||||
let payload = b"0123456789abcdef";
|
||||
let (clip_uri, base_uri) = write_local_payload(tmp.path(), "clip.mp4", payload);
|
||||
let db = connect(tmp.path().join("db").to_str().unwrap())
|
||||
.execute()
|
||||
.await?;
|
||||
|
||||
let table = db
|
||||
.create_table(
|
||||
"videos",
|
||||
range_uri_batch(&[1], &[clip_uri.as_str()], &[Some(0)], &[Some(6)]),
|
||||
)
|
||||
.initial_bases(vec![local_base(1, base_uri.clone())])
|
||||
.execute()
|
||||
.await?;
|
||||
|
||||
assert_eq!(table.version().await?, 1);
|
||||
let manifest = table.as_native().unwrap().manifest().await?;
|
||||
let registered = manifest.base_paths.get(&1).expect("base 1 registered");
|
||||
assert_eq!(registered.path, base_uri);
|
||||
assert!(!registered.is_dataset_root);
|
||||
|
||||
let reopened = db.open_table("videos").execute().await?;
|
||||
let ids = collect_row_ids(&reopened).await?;
|
||||
let files = reopened.fetch_blob_files("image", &ids).await?;
|
||||
let file = files[0].as_ref().unwrap();
|
||||
assert_eq!(file.uri(), Some("clip.mp4"));
|
||||
assert_eq!(file.position(), Some(0));
|
||||
assert_eq!(file.size(), 6);
|
||||
let bytes = reopened.fetch_blobs("image", &ids).await?;
|
||||
assert_eq!(bytes.value(0), &payload[..6]);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn create_table_with_data_accepts_unregistered_uri_only_with_opt_in() -> Result<()> {
|
||||
let tmp = tempdir().unwrap();
|
||||
let payload = b"0123456789abcdef";
|
||||
let (clip_uri, _) = write_local_payload(tmp.path(), "clip.mp4", payload);
|
||||
let db = connect(tmp.path().join("db").to_str().unwrap())
|
||||
.execute()
|
||||
.await?;
|
||||
let batch = range_uri_batch(&[1], &[clip_uri.as_str()], &[Some(0)], &[Some(6)]);
|
||||
|
||||
let err = db
|
||||
.create_table("videos", batch.clone())
|
||||
.execute()
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(
|
||||
err.to_string()
|
||||
.contains("allow_external_blob_outside_bases"),
|
||||
"got: {err}"
|
||||
);
|
||||
assert!(db.open_table("videos").execute().await.is_err());
|
||||
|
||||
let table = db
|
||||
.create_table("videos", batch)
|
||||
.allow_external_blob_outside_bases(true)
|
||||
.execute()
|
||||
.await?;
|
||||
assert_eq!(table.version().await?, 1);
|
||||
let reopened = db.open_table("videos").execute().await?;
|
||||
let ids = collect_row_ids(&reopened).await?;
|
||||
let bytes = reopened.fetch_blobs("image", &ids).await?;
|
||||
assert_eq!(bytes.value(0), &payload[..6]);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// An explicit `id=0` asks Lance to assign the base ID in the create commit.
|
||||
#[tokio::test]
|
||||
async fn create_empty_table_with_initial_bases_bootstraps_base_with_auto_id() -> Result<()> {
|
||||
let tmp = tempdir().unwrap();
|
||||
let payload = b"payload-bytes";
|
||||
let (clip_uri, base_uri) = write_local_payload(tmp.path(), "clip.mp4", payload);
|
||||
let db = connect(tmp.path().join("db").to_str().unwrap())
|
||||
.execute()
|
||||
.await?;
|
||||
|
||||
let table = db
|
||||
.create_empty_table("videos", wide_blob_table_schema())
|
||||
.initial_bases(vec![local_base(0, base_uri.clone())])
|
||||
.execute()
|
||||
.await?;
|
||||
let manifest = table.as_native().unwrap().manifest().await?;
|
||||
let registered = manifest
|
||||
.base_paths
|
||||
.values()
|
||||
.find(|base| base.path == base_uri)
|
||||
.expect("base registered with the empty create");
|
||||
assert!(registered.id > 0);
|
||||
assert!(!registered.is_dataset_root);
|
||||
|
||||
table
|
||||
.add(range_uri_batch(
|
||||
&[1],
|
||||
&[clip_uri.as_str()],
|
||||
&[None],
|
||||
&[None],
|
||||
))
|
||||
.execute()
|
||||
.await?;
|
||||
let reopened = db.open_table("videos").execute().await?;
|
||||
let ids = collect_row_ids(&reopened).await?;
|
||||
let files = reopened.fetch_blob_files("image", &ids).await?;
|
||||
assert_eq!(files[0].as_ref().unwrap().uri(), Some("clip.mp4"));
|
||||
let bytes = reopened.fetch_blobs("image", &ids).await?;
|
||||
assert_eq!(bytes.value(0), payload);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Scoped `base_<id>.<key>` options travel with the table and keep each base
|
||||
/// readable after reopen. Unscoped options stay shared defaults.
|
||||
#[tokio::test]
|
||||
async fn created_bases_read_back_with_scoped_storage_options() -> Result<()> {
|
||||
let tmp = tempdir().unwrap();
|
||||
let payload_a = b"base-a-payload";
|
||||
let payload_b = b"base-b-payload";
|
||||
let dir_a = tmp.path().join("base-a");
|
||||
let dir_b = tmp.path().join("base-b");
|
||||
std::fs::create_dir_all(&dir_a).unwrap();
|
||||
std::fs::create_dir_all(&dir_b).unwrap();
|
||||
let (uri_a, base_a) = write_local_payload(&dir_a, "clip.mp4", payload_a);
|
||||
let (uri_b, base_b) = write_local_payload(&dir_b, "clip.mp4", payload_b);
|
||||
let storage_options = [
|
||||
("timeout", "7s"),
|
||||
("base_1.region", "base-one"),
|
||||
("base_2.region", "base-two"),
|
||||
];
|
||||
let db = connect(tmp.path().join("db").to_str().unwrap())
|
||||
.execute()
|
||||
.await?;
|
||||
|
||||
let table = db
|
||||
.create_table(
|
||||
"videos",
|
||||
range_uri_batch(
|
||||
&[1, 2],
|
||||
&[uri_a.as_str(), uri_b.as_str()],
|
||||
&[None, None],
|
||||
&[None, None],
|
||||
),
|
||||
)
|
||||
.initial_bases(vec![local_base(1, base_a), local_base(2, base_b)])
|
||||
.storage_options(storage_options)
|
||||
.execute()
|
||||
.await?;
|
||||
assert_eq!(table.version().await?, 1);
|
||||
|
||||
let reopened = db
|
||||
.open_table("videos")
|
||||
.storage_options(storage_options)
|
||||
.execute()
|
||||
.await?;
|
||||
let ids = collect_row_ids(&reopened).await?;
|
||||
let files = reopened.fetch_blob_files("image", &ids).await?;
|
||||
assert_eq!(files[0].as_ref().unwrap().uri(), Some("clip.mp4"));
|
||||
assert_eq!(files[1].as_ref().unwrap().uri(), Some("clip.mp4"));
|
||||
let bytes = reopened.fetch_blobs("image", &ids).await?;
|
||||
assert_eq!(bytes.value(0), payload_a);
|
||||
assert_eq!(bytes.value(1), payload_b);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Scoped `base_<id>.<key>` options belong to exactly one base. An option
|
||||
/// that only base 1 can reject must not change what base 2 reads on reopen.
|
||||
#[tokio::test]
|
||||
async fn scoped_storage_options_do_not_leak_between_bases_on_reopen() -> Result<()> {
|
||||
let tmp = tempdir().unwrap();
|
||||
let payload_a = b"base-a-payload";
|
||||
let payload_b = b"base-b-payload";
|
||||
let dir_a = tmp.path().join("base-a");
|
||||
let dir_b = tmp.path().join("base-b");
|
||||
std::fs::create_dir_all(&dir_a).unwrap();
|
||||
std::fs::create_dir_all(&dir_b).unwrap();
|
||||
let (uri_a, base_a) = write_local_payload(&dir_a, "clip.mp4", payload_a);
|
||||
let (uri_b, base_b) = write_local_payload(&dir_b, "clip.mp4", payload_b);
|
||||
let db = connect(tmp.path().join("db").to_str().unwrap())
|
||||
.execute()
|
||||
.await?;
|
||||
|
||||
db.create_table(
|
||||
"videos",
|
||||
range_uri_batch(
|
||||
&[1, 2],
|
||||
&[uri_a.as_str(), uri_b.as_str()],
|
||||
&[None, None],
|
||||
&[None, None],
|
||||
),
|
||||
)
|
||||
.initial_bases(vec![local_base(1, base_a), local_base(2, base_b)])
|
||||
.execute()
|
||||
.await?;
|
||||
|
||||
let reopened = db
|
||||
.open_table("videos")
|
||||
.storage_options([("base_1.scheduler_error_mode", "invalid")])
|
||||
.execute()
|
||||
.await?;
|
||||
let pairs = sorted_id_rowid(&reopened).await?;
|
||||
let row_for = |id: i64| {
|
||||
pairs
|
||||
.iter()
|
||||
.find(|(row_id, _)| *row_id == id)
|
||||
.map(|(_, row_id)| *row_id)
|
||||
.expect("row present")
|
||||
};
|
||||
|
||||
let err = reopened
|
||||
.fetch_blobs("image", &[row_for(1)])
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(
|
||||
err.to_string().contains("scheduler_error_mode"),
|
||||
"base 1 should carry its scoped option, got: {err}"
|
||||
);
|
||||
let bytes = reopened.fetch_blobs("image", &[row_for(2)]).await?;
|
||||
assert_eq!(bytes.value(0), payload_b);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn namespace_properties(root: &std::path::Path) -> std::collections::HashMap<String, String> {
|
||||
std::collections::HashMap::from([("root".to_string(), root.to_str().unwrap().to_string())])
|
||||
}
|
||||
|
||||
/// Connection-level storage options must be merged under the request's
|
||||
/// storage options on the namespace create path. Replacing the request
|
||||
/// accessor drops `base_<id>.<key>` settings and silently accepts options the
|
||||
/// selected base cannot use.
|
||||
#[tokio::test]
|
||||
async fn namespace_create_keeps_caller_scoped_storage_options() -> Result<()> {
|
||||
let tmp = tempdir().unwrap();
|
||||
let (uri, base_uri) = write_local_payload(tmp.path(), "clip.mp4", b"namespace-scoped");
|
||||
let db = connect_namespace("dir", namespace_properties(&tmp.path().join("ns")))
|
||||
.storage_options([("timeout", "7s")])
|
||||
.execute()
|
||||
.await?;
|
||||
|
||||
let err = db
|
||||
.create_table(
|
||||
"videos",
|
||||
range_uri_batch(&[1], &[uri.as_str()], &[None], &[None]),
|
||||
)
|
||||
.initial_bases(vec![local_base(1, base_uri)])
|
||||
.storage_option("base_1.scheduler_error_mode", "invalid")
|
||||
.execute()
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(
|
||||
err.to_string().contains("scheduler_error_mode"),
|
||||
"request-scoped option was dropped, got: {err}"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A namespace reopen keeps scoped options attached to their own base: base
|
||||
/// 1's invalid option fails its read while base 2 still returns exact bytes.
|
||||
#[tokio::test]
|
||||
async fn namespace_reopen_applies_scoped_options_to_their_own_base() -> Result<()> {
|
||||
let tmp = tempdir().unwrap();
|
||||
let payload_a = b"namespace-base-a";
|
||||
let payload_b = b"namespace-base-b";
|
||||
let dir_a = tmp.path().join("base-a");
|
||||
let dir_b = tmp.path().join("base-b");
|
||||
std::fs::create_dir_all(&dir_a).unwrap();
|
||||
std::fs::create_dir_all(&dir_b).unwrap();
|
||||
let (uri_a, base_a) = write_local_payload(&dir_a, "clip.mp4", payload_a);
|
||||
let (uri_b, base_b) = write_local_payload(&dir_b, "clip.mp4", payload_b);
|
||||
let db = connect_namespace("dir", namespace_properties(&tmp.path().join("ns")))
|
||||
.storage_options([("timeout", "7s")])
|
||||
.execute()
|
||||
.await?;
|
||||
|
||||
db.create_table(
|
||||
"videos",
|
||||
range_uri_batch(
|
||||
&[1, 2],
|
||||
&[uri_a.as_str(), uri_b.as_str()],
|
||||
&[None, None],
|
||||
&[None, None],
|
||||
),
|
||||
)
|
||||
.initial_bases(vec![local_base(1, base_a), local_base(2, base_b)])
|
||||
.execute()
|
||||
.await?;
|
||||
|
||||
let reopened = db
|
||||
.open_table("videos")
|
||||
.storage_options([("base_1.scheduler_error_mode", "invalid")])
|
||||
.execute()
|
||||
.await?;
|
||||
let pairs = sorted_id_rowid(&reopened).await?;
|
||||
let row_for = |id: i64| {
|
||||
pairs
|
||||
.iter()
|
||||
.find(|(row_id, _)| *row_id == id)
|
||||
.map(|(_, row_id)| *row_id)
|
||||
.expect("row present")
|
||||
};
|
||||
|
||||
let err = reopened
|
||||
.fetch_blobs("image", &[row_for(1)])
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(
|
||||
err.to_string().contains("scheduler_error_mode"),
|
||||
"base 1 should carry its scoped option, got: {err}"
|
||||
);
|
||||
let bytes = reopened.fetch_blobs("image", &[row_for(2)]).await?;
|
||||
assert_eq!(bytes.value(0), payload_b);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user