Files
lancedb/docs/web-tests/py/test_quickstart.py
T
Brendan Clement 27b7a248e4 docs: use refresh_column_async with wait on Enterprise pages (#5183)
## The problem

Several Python examples on Enterprise pages start a computed column
refresh with `table.refresh_column(...)`. On a LanceDB Enterprise
connection that call always fails:

```
NotImplementedError: not supported: a remote refresh runs as a server job; use refresh_column_async and wait on the returned handle
```

On Enterprise a refresh runs as a job on the server. Only
`refresh_column_async(...)` works there: it returns a job, and
`job.wait()` blocks until the job finishes. A reader following the
quickstart's Enterprise step, or the secrets or GPU examples, hits the
error. The same fix landed for the Sophon-owned page in
lancedb/sophon#10478.

## What this changes

- **The examples use the job form:** `job =
table.refresh_column_async(...)` then `job.wait()`. This covers
`curation/vend-secret.mdx`, `curation/create-function.mdx` and the
quickstart, plus the sentences that named the blocking call in
`enterprise/auto-refresh.mdx` and
`feature-engineering/add-computed-column.mdx`.
- **The quickstart example now comes from a test.** The
`PyQuickstartAddFeature` snippet is generated from the deployment test
in `docs/web-tests/py/test_quickstart.py`, and the separate
Enterprise-only snippet is folded into it. That test also asserts that
the blocking call raises an error naming `refresh_column_async`.
- **The GPU example only shows arguments the Enterprise table accepts
today.** `gpu_class` and `gpu_count` are dropped from `add_columns`, and
`gpu_count` from the refresh call, with a one-sentence note. See "Python
wrapper gap" below.

## How it was checked

Every Enterprise call the changed pages show was run through the Python
SDK (0.42.0b26, built from this branch) against a local stand-in for an
Enterprise server that returns canned responses:

- `table.refresh_column("embedding")` raises the error above and sends
no request.
- `job = table.refresh_column_async("embedding"); job.wait()` submits a
refresh job and returns its result.
- `table.refresh_column_async("embedding", gpu_class="h100",
total_gpu_count=8).wait()` is accepted, and the server receives both GPU
options.
- The removed forms fail as expected: `gpu_count` on
`refresh_column_async`, and `gpu_class` or `gpu_count` on `add_columns`,
raise `TypeError: unexpected keyword argument`.

Also: the committed quickstart snippet matches what the generator
produces from the test, and the five changed pages render with no
blocking call in a local preview.

**Not run:** the quickstart deployment test itself. It needs a real
Enterprise deployment and is skipped without credentials, which CI does
not have. Registering a Function also needs a real deployment, so that
line of the GPU example was not exercised.

## Python wrapper gap (to be fixed separately)

The Python `RemoteTable.refresh_column_async` and
`RemoteTable.add_columns` do not accept `gpu_count`, and `add_columns`
also does not accept `gpu_class`. The Rust remote table supports these
GPU placement options, so this looks like an oversight in the Python
layer. This PR makes no SDK change. Once the wrapper passes them
through, the GPU example can show them again.

## Risk

Low. Docs and docs tests only.

## Pipeline

Updates from [git push
no-mistakes](https://github.com/kunchenguid/no-mistakes)

<!-- no-mistakes-pipeline-attestation:v1
{"head_sha":"11ac1a260e8825dd406dea4e839f2498309e843b","steps":[{"step":"intent","status":"completed"},{"step":"rebase","status":"completed"},{"step":"review","status":"completed"},{"step":"test","status":"completed"},{"step":"document","status":"completed"},{"step":"lint","status":"completed"},{"step":"push","status":"completed"},{"step":"pr","status":"running"},{"step":"ci","status":"pending"}],"live_validation":{"verdict":"go","live":7,"total":9}}
-->

<details>
<summary>✅ **Intent** - passed</summary>

✅ No issues found.
</details>

<details>
<summary>✅ **Rebase** - passed</summary>

✅ No issues found.
</details>

<details>
<summary>✅ **Review** - passed</summary>

✅ No issues found.
</details>

<details>
<summary>⚠️ **Test** - 2 infos</summary>

- ⚠️ `docs/web/curation/create-function.mdx:546` - Not confirmed live.
The new example calls `table.refresh_column_async(&#34;embedding&#34;,
gpu_class=&#34;h100&#34;, gpu_count=4, total_gpu_count=8)`, but
`RemoteTable.refresh_column_async` in
python/python/lancedb/remote/table.py (line 1280) has no `gpu_count`
parameter (only `gpu_class` and `total_gpu_count`), while the abstract
`Table` and `LanceTable` do. If that reading holds, the documented call
raises `TypeError: unexpected keyword argument &#39;gpu_count&#39;` on
Enterprise. The blocking `RemoteTable.refresh_column` has the same gap,
so this predates the change, but the page still shows a call that may
not run. Decision needed: drop `gpu_count=4` from the example, or add
the parameter to the Enterprise table (an SDK change beyond this docs
change).
- ⚠️ The intent asked whether the docs change can be validated by
running code. In this run it could not: the SDK build did not finish in
the time budget and no Enterprise deployment credentials are available,
so the only test covering the changed quickstart snippet
(`test_quickstart_derived_feature_on_a_deployment`) skips. The prepared
driver script in the evidence directory exercises the three documented
calls against a localhost emulator once the SDK is built.
- ⚠️ live validation verdict: inconclusive (4 of 7 scenarios were driven
live against the product); untested: On an Enterprise connection
(localhost emulator, synthetic responses) the documented `job =
table.refresh_column_async(&#34;embedding&#34;); job.wait()` completes,
and the old blocking `table.refresh_column(...)` raises
NotImplementedError naming refresh_column_async, On an Enterprise
connection the create-function.mdx example
`table.refresh_column_async(&#34;embedding&#34;,
gpu_class=&#34;h100&#34;, gpu_count=4, total_gpu_count=8)` is accepted
and submits a job, `test_quickstart_derived_feature_on_a_deployment`
passes against a real LanceDB Enterprise deployment
- Live validation: ⚠️ inconclusive - 4 of 7 scenarios driven live
against the product

| Scenario | Result | Live | Evidence |
| --- | --- | --- | --- |
| Reader opens the six changed docs pages in the local Mintlify preview
and sees the job form (`refresh_column_async` + `job.wait()`) with no
blocking `table.refresh_column(` call left | ✅ pass | live |
Rendered-page check output (artifact &#39;Rendered docs check&#39;) and
saved HTML under
~/.no-mistakes/evidence/01M85TWQ599ZJ5NQ0DBASSFT91/rendered |
| Reader follows the new `refresh_column_async` link on the
computed-column page and lands on the &#39;Run a refresh on
Enterprise&#39; section | ✅ pass | live | Rendered add-computed-column
page links to /feature-engineering/refresh-column#async; the rendered
refresh-column page (HTTP 200) contains an element with
id=&#34;async&#34; |
| Quickstart page still renders after the Enterprise-only snippet import
was removed, and its feature step shows the job form | ✅ pass | live |
quickstart returns HTTP 200; page payload contains `job =
table.refresh_column_async(&#34;quality_score&#34;)\njob.wait()`; no
`PyQuickstartAddFeatureEnterprise` reference remains |
| Regenerating snippets from docs/web-tests/py/test_quickstart.py
reproduces the committed `PyQuickstartAddFeature` snippet | ✅ pass |
live | `mdx_snippets_gen.py` output in
~/.no-mistakes/evidence/01M85TWQ599ZJ5NQ0DBASSFT91/snippets-regen/quickstart.mdx
is identical to docs/web/snippets/quickstart.mdx for that export |
| On an Enterprise connection (localhost emulator, synthetic responses)
the documented `job = table.refresh_column_async(&#34;embedding&#34;);
job.wait()` completes, and the old blocking `table.refresh_column(.… |
⏸️ untested | no | Needs the Python SDK built from this worktree. `uv
run ... maturin develop` started from a cold cargo cache and was still
compiling after about 18 minutes, so I stopped it to stay inside the
30-minute… |
| On an Enterprise connection the create-function.mdx example
`table.refresh_column_async(&#34;embedding&#34;,
gpu_class=&#34;h100&#34;, gpu_count=4, total_gpu_count=8)` is accepted
and submits a job | ⏸️ untested | no | Blocked by the same unfinished
SDK build. The source suggests this call would raise TypeError (see
finding), but that was not executed. |
| `test_quickstart_derived_feature_on_a_deployment` passes against a
real LanceDB Enterprise deployment | ⏸️ untested | no | The test skips
unless LANCEDB_DOCS_TEST_DEPLOYMENT=1 and LANCEDB_URI,
LANCEDB_HOST_OVERRIDE and LANCEDB_API_KEY point at a deployment with a
Function catalog; a localhost emulator cannot stand in for… |

- <code>`cd docs/web &amp;&amp; mint dev --port 3391 --no-open`, then
`curl http://localhost:3391/&lt;page&gt;` for quickstart,
curation/vend-secret, curation/create-function, enterprise/auto-refresh,
feature-engineering/add-computed-column,
feature-engineering/refresh-column (all HTTP 200), with a text check of
each rendered page</code>
- <code>`python3 docs/web-tests/mdx_snippets_gen.py -s docs/web-tests/py
-s docs/web-tests/ts -s docs/web-tests/rs -o
&lt;evidence&gt;/snippets-regen`, then diff of `PyQuickstartAddFeature`
against `docs/web/snippets/quickstart.mdx`</code>
- <code>`cd python &amp;&amp; uv run --extra tests --extra dev maturin
develop --extras tests,dev` (started, not finished within budget,
stopped; no result)</code>
- <code>`chrome-devtools-axi` screenshots of the rendered pages (failed:
BRIDGE_NOT_READY)</code>
- <code>Source read of `python/python/lancedb/remote/table.py`
`refresh_column_async` signature against the create-function.mdx example
(not live)</code>

🔧 Fix applied.
2 infos still open:

- ℹ️ No screenshots of the rendered docs pages were captured.
`chrome-devtools-axi` failed with &#34;Bridge failed to start within
30s&#34; and headless Google Chrome hung until killed at 60s per page.
The pages were instead fetched as served HTML from a local `mint dev`
preview and saved under rendered-round2/. For the quickstart page the
job-form snippet is present only in the page&#39;s hydration payload,
not as rendered text, so its on-screen appearance was not seen.
- ℹ️ `docs/web-tests/py/test_quickstart.py:347` -
`test_quickstart_derived_feature_on_a_deployment`, the only test that
runs the changed quickstart snippet end to end, skips because no
Enterprise deployment credentials exist (LANCEDB_DOCS_TEST_DEPLOYMENT,
LANCEDB_URI, LANCEDB_HOST_OVERRIDE, LANCEDB_API_KEY). The same calls
were driven against a localhost emulator instead, which does not prove
real-deployment behaviour.
- Live validation: ✅ go - 7 of 9 scenarios driven live against the
product

| Scenario | Result | Live | Evidence |
| --- | --- | --- | --- |
| On an Enterprise connection (Python SDK, localhost emulator, synthetic
responses) the documented `job =
table.refresh_column_async(&#34;embedding&#34;); job.wait()` submits a
refresh job and returns its resul… | ✅ pass | live |
driver-output-round2.txt: OK -&gt; rows_assigned=3 ...; server received
POST /v1/table/test/backfill_column {&#39;column&#39;:
&#39;embedding&#39;} |
| Adversarial: on the same Enterprise connection the old blocking
`table.refresh_column(&#34;embedding&#34;)` fails with
NotImplementedError naming refresh_column_async and sends no request | ✅
pass | live | driver-output-round2.txt: RAISED NotImplementedError: ...
use refresh_column_async and wait on the returned handle; requests sent:
[] |
| The create-function.mdx refresh example as now written,
`refresh_column_async(&#34;embedding&#34;, gpu_class=&#34;h100&#34;,
total_gpu_count=8)` then `job.wait()`, is accepted on Enterprise and
sends both GPU options | ✅ pass | live | driver-output-round2.txt:
server received {&#39;gpu_class&#39;: &#39;h100&#39;,
&#39;total_gpu_count&#39;: 8, &#39;column&#39;: &#39;embedding&#39;} |
| The create-function.mdx `table.add_columns({&#34;embedding&#34;:
&lt;Function binding&gt;}, total_gpu_count=8)` is accepted on Enterprise
and sends the fleet GPU ceiling | ✅ pass | live |
driver-output-round2.txt: OK -&gt; AddColumnsResult(version=2); POST
/v1/table/test/add_columns/ body carries the Function binding and
&#39;total_gpu_count&#39;: 8 |
| Adversarial: the GPU arguments removed from the create-function.mdx
example (`gpu_count` on refresh_column_async; `gpu_class`/`gpu_count` on
add_columns) are rejected by the Enterprise table, matching… | ✅ pass |
live | driver-output-round2.txt: TypeError unexpected keyword argument
&#39;gpu_count&#39; (refresh_column_async) and &#39;gpu_class&#39;
(add_columns) |
| The committed `PyQuickstartAddFeature` snippet equals what the snippet
generator produces from docs/web-tests/py/test_quickstart.py | ✅ pass |
live | `mdx_snippets_gen.py` output in snippets-regen-round2; `diff -r`
against docs/web/snippets reports no difference for quickstart.mdx |
| A reader opening the five changed pages in a local Mintlify preview
sees the job form and no blocking `table.refresh_column(` call | ✅ pass
| live | rendered-round2-counts.txt and rendered-round2/*.html: all five
pages return 200 with zero blocking calls; job form present on each |
| `test_quickstart_derived_feature_on_a_deployment` passes against a
real LanceDB Enterprise deployment | ⏸️ untested | no | Ran the test; it
skips because no Enterprise deployment credentials exist here. A
localhost emulator cannot stand in: the test registers a Function over
Flight SQL and computes real values. To run it,… |
| `version = db.create_function(embed)` from the create-function.mdx
example registers a Function on Enterprise | ⏸️ untested | no | Tried it
against the emulator; the call goes over Flight SQL to a Function
catalog, which only a real Enterprise deployment provides. This line is
unchanged by the diff. Needs the same deployment cred… |

- <code>`~/.treehouse/lancedb-9ea8c9/1/lancedb/python/.venv/bin/python
drive_enterprise_refresh_v3.py` (lancedb 0.42.0b26 built at cb082c08,
whose SDK source is identical to this head; Enterprise connection to a
localhost emulator with synthetic responses)</code>
- <code>`python docs/web-tests/mdx_snippets_gen.py -s docs/web-tests/py
-s docs/web-tests/ts -s docs/web-tests/rs -o
&lt;evidence&gt;/snippets-regen-round2` then `diff -r` against
`docs/web/snippets` (quickstart.mdx identical)</code>
- <code>`cd docs/web-tests/py &amp;&amp; python -m pytest
test_quickstart.py -q -rs` (4 passed, 6 skipped; all skips are
deployment-only tests)</code>
- <code>`mint dev --port 3397` in docs/web, then `curl` of /quickstart,
/curation/vend-secret, /curation/create-function,
/enterprise/auto-refresh, /feature-engineering/add-computed-column (all
200) and a count of blocking vs job-form calls in the served HTML</code>
- <code>`git status --short` after teardown (clean; preview stopped,
port 3397 free)</code>
</details>

<details>
<summary>✅ **Document** - passed</summary>

✅ No issues found.
</details>

<details>
<summary>⚠️ **Lint** - 1 info</summary>

- ℹ️ `docs/web-tests/py/test_quickstart.py:29` - `ruff check` reports
C408 (`dict()` call, rewrite as a literal) in the `deployment` fixture.
It is on a line this change did not touch and is also present at the
base commit; ruff&#39;s only fix for it is marked unsafe, so I left it.
`ruff format --check` passes. ruff is not on PATH, so I ran it through
`uvx`, which may not be the repo-pinned version.
</details>

<details>
<summary>✅ **Push** - passed</summary>

✅ No issues found.
</details>
2026-11-24 09:31:06 -08:00

437 lines
15 KiB
Python

# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
import os
import shutil
import uuid
from pathlib import Path
import lancedb
import pytest
import pytest_asyncio
# What the quickstart's download step leaves in an application's directory.
IMAGE = (
Path(__file__).resolve().parents[2]
/ "web/static/assets/images/quickstart/sir-lancelot.jpg"
)
DEPLOYMENT = ("LANCEDB_URI", "LANCEDB_HOST_OVERRIDE", "LANCEDB_API_KEY")
# The connection settings alone never send these tests to a deployment.
OPT_IN = "LANCEDB_DOCS_TEST_DEPLOYMENT"
def deployment_settings():
if os.environ.get(OPT_IN) != "1":
pytest.skip(f"set {OPT_IN}=1 and {', '.join(DEPLOYMENT)} to use a deployment")
missing = [name for name in DEPLOYMENT if not os.environ.get(name)]
if missing:
pytest.fail(f"{OPT_IN}=1 needs {', '.join(missing)}")
return dict(
uri=os.environ["LANCEDB_URI"],
api_key=os.environ["LANCEDB_API_KEY"],
region=os.environ.get("LANCEDB_REGION", "us-east-1"),
host_override=os.environ["LANCEDB_HOST_OVERRIDE"],
)
class OwnedTables:
"""A deployment connection on which a test creates only tables of its own.
Each name gets a suffix unique to the test and is claimed only while no
table has it; the test drops what it claimed, whether or not it passed.
"""
def __init__(self, db):
self.db = db
self.suffix = uuid.uuid4().hex[:12]
self.claimed = []
self.claimed_namespaces = []
def claim(self, name, existing, mode):
owned = f"{name}_{self.suffix}"
if owned in self.claimed:
return owned, mode
if owned in existing:
raise RuntimeError(f"{owned} already exists and is not this test's")
self.claimed.append(owned)
return owned, "create"
def table_names(self):
names, token = [], None
while True:
page = self.db.list_tables(page_token=token)
names += page.tables
if not (token := page.page_token):
return names
def create_table(self, name, *args, mode="create", **kwargs):
owned, mode = self.claim(name, self.table_names(), mode)
return self.db.create_table(owned, *args, mode=mode, **kwargs)
def claim_namespace(self):
"""A namespace only this test can see, for SQL text that must show
readers a literal, unqualified table name (so suffixing the name
itself, as `claim` does, isn't an option). The namespace is created
exclusively (no check-then-act): a collision raises instead of
silently sharing someone else's. `drop_claimed` cascades through it,
so individual tables and views inside never need their own claim.
"""
namespace_path = [f"quickstart_{self.suffix}"]
self.db.create_namespace(namespace_path, mode="create")
self.claimed_namespaces.append(namespace_path)
return NamespacedDB(self.db, namespace_path)
def drop_claimed(self):
existing = self.table_names()
for name in self.claimed:
if name in existing:
self.db.drop_table(name)
for namespace_path in self.claimed_namespaces:
self.db.drop_namespace(namespace_path, mode="skip", behavior="cascade")
class NamespacedDB:
"""A `db.create_table` / `db.execute_query` view scoped to one namespace."""
def __init__(self, db, namespace_path):
self.db = db
self.namespace_path = namespace_path
def create_table(self, name, *args, **kwargs):
kwargs.setdefault("namespace_path", self.namespace_path)
return self.db.create_table(name, *args, **kwargs)
def execute_query(self, query, **kwargs):
kwargs.setdefault("default_namespace_path", self.namespace_path)
return self.db.execute_query(query, **kwargs)
class AsyncOwnedTables(OwnedTables):
async def table_names(self):
names, token = [], None
while True:
page = await self.db.list_tables(page_token=token)
names += page.tables
if not (token := page.page_token):
return names
async def create_table(self, name, *args, mode="create", **kwargs):
owned, mode = self.claim(name, await self.table_names(), mode)
return await self.db.create_table(owned, *args, mode=mode, **kwargs)
async def drop_claimed(self):
existing = await self.table_names()
for name in self.claimed:
if name in existing:
await self.db.drop_table(name)
@pytest.fixture
def deployment():
owned = OwnedTables(lancedb.connect(**deployment_settings()))
yield owned
owned.drop_claimed()
@pytest.fixture(params=["local", "enterprise"])
def db(request, db_path_factory):
if request.param == "local":
yield lancedb.connect(db_path_factory("quickstart_db"))
else:
yield request.getfixturevalue("deployment")
@pytest_asyncio.fixture(params=["local", "enterprise"])
async def async_db(request, db_path_factory):
if request.param == "local":
yield await lancedb.connect_async(db_path_factory("quickstart_async_db"))
return
owned = AsyncOwnedTables(await lancedb.connect_async(**deployment_settings()))
yield owned
await owned.drop_claimed()
def create_frames(db):
# --8<-- [start:quickstart_data]
data = [
{
"frame_id": "1",
"video_id": "clip-1",
"caption": "a robot arm reaching toward a cup",
"stats": {"motion": 3, "sharpness": 4, "exposure": 4, "framing": 3},
"embedding": [0.7, 0.1, 0.9, 0.7],
},
{
"frame_id": "2",
"video_id": "clip-1",
"caption": "a two-finger gripper closing on a cup",
"stats": {"motion": 5, "sharpness": 4, "exposure": 5, "framing": 2},
"embedding": [0.2, 0.9, 0.4, 0.9],
},
{
"frame_id": "3",
"video_id": "clip-2",
"caption": "a robot arm holding a cup steady",
"stats": {"motion": 2, "sharpness": 3, "exposure": 3, "framing": 4},
"embedding": [0.9, 0.1, 0.5, 0.4],
},
]
# --8<-- [end:quickstart_data]
# --8<-- [start:quickstart_create_table]
table = db.create_table("frames", data=data, mode="overwrite")
# --8<-- [end:quickstart_create_table]
assert table.count_rows() == 3
# --8<-- [start:quickstart_add_data]
table.add(
[
{
"frame_id": "4",
"video_id": "clip-2",
"caption": "a gripper lowering a cup onto the table",
"stats": {"motion": 5, "sharpness": 4, "exposure": 4, "framing": 2},
"embedding": [0.3, 0.9, 0.6, 0.8],
}
]
)
# --8<-- [end:quickstart_add_data]
assert table.count_rows() == 4
return table
def test_quickstart(db):
table = create_frames(db)
# --8<-- [start:quickstart_vector_search_1]
# Search for frames similar to "a gripper closing on an object"
query_vector = [0.2, 0.8, 0.4, 0.9]
# Ensure you run `pip install polars` beforehand
result = (
table.search(query_vector)
.select(["frame_id", "video_id", "caption", "_distance"])
.limit(2)
.to_polars()
)
print(result)
# --8<-- [end:quickstart_vector_search_1]
assert result["frame_id"].to_list() == ["2", "4"]
# --8<-- [start:quickstart_output_pandas]
# Ensure you run `pip install pandas` beforehand
result = table.search(query_vector).limit(2).to_pandas()
print(result)
# --8<-- [end:quickstart_output_pandas]
assert result["frame_id"].to_list() == ["2", "4"]
@pytest.mark.asyncio
async def test_quickstart_async_api(async_db):
data = [
{
"frame_id": "2",
"video_id": "clip-1",
"caption": "a two-finger gripper closing on a cup",
"stats": {"motion": 5, "sharpness": 4, "exposure": 5, "framing": 2},
"embedding": [0.2, 0.9, 0.4, 0.9],
}
]
# --8<-- [start:quickstart_create_table_async]
async_table = await async_db.create_table(
"frames",
data=data,
mode="overwrite",
)
# --8<-- [end:quickstart_create_table_async]
# --8<-- [start:quickstart_vector_search_1_async]
# Search for frames similar to "a gripper closing on an object"
query_vector = [0.2, 0.8, 0.4, 0.9]
# Ensure you run `pip install polars` beforehand
async_result = (
await (await async_table.search(query_vector))
.select(["frame_id", "video_id", "caption", "_distance"])
.limit(2)
.to_polars()
)
print(async_result)
# --8<-- [end:quickstart_vector_search_1_async]
assert async_result["frame_id"].to_list() == ["2"]
def test_quickstart_curate_with_sql(deployment):
# create_frames and the dedupe statement below name tables directly, to
# keep the extracted snippets reading like the quickstart. Run inside a
# namespace only this test can see, so a concurrent run can never
# overwrite this run's 'frames' or drop it out from under this one.
db = deployment.claim_namespace()
table = create_frames(db)
# --8<-- [start:quickstart_curate_sample]
sample = db.execute_query(
"SELECT frame_id FROM frames TABLESAMPLE (2 ROWS)"
).read_all()
print(sample.to_pylist())
# --8<-- [end:quickstart_curate_sample]
assert sample.num_rows == 2
# --8<-- [start:quickstart_curate_dedupe_setup]
# Frame 5 is a near-duplicate of frame 2: the gripper is still closing,
# one video frame later, with an almost identical embedding.
table.add(
[
{
"frame_id": "5",
"video_id": "clip-1",
"caption": "the two-finger gripper still closing on the cup",
"stats": {"motion": 5, "sharpness": 4, "exposure": 5, "framing": 2},
"embedding": [0.2, 0.9, 0.4, 0.89],
}
]
)
from lancedb.index import IvfFlat
table.create_index(
"embedding", config=IvfFlat(num_partitions=1, distance_type="l2")
)
table.wait_for_index(["embedding_idx"])
# --8<-- [end:quickstart_curate_dedupe_setup]
# --8<-- [start:quickstart_curate_dedupe]
db.execute_query("""
CREATE MATERIALIZED VIEW frames_deduped AS
SELECT * FROM dedupe(
'frames',
'embedding',
distance_threshold => 0.03
)
""")
# --8<-- [end:quickstart_curate_dedupe]
# --8<-- [start:quickstart_curate_dedupe_query]
deduped = db.execute_query(
"SELECT frame_id FROM frames_deduped ORDER BY frame_id"
).read_all()
print(deduped.to_pylist())
# --8<-- [end:quickstart_curate_dedupe_query]
assert deduped.column("frame_id").to_pylist() in (
["1", "2", "3", "4"],
["1", "3", "4", "5"],
)
def quality_scores(table):
rows = table.search().select(["frame_id", "video_id", "quality_score"]).to_list()
return {row["frame_id"]: row["quality_score"] for row in rows}
EXPECTED_QUALITY_SCORES = {"1": 3.5, "2": 4.0, "3": 3.0, "4": 3.75}
def flatten_stats(table):
# --8<-- [start:quickstart_flatten_stats]
table.add_columns(
{
"motion": "cast(stats.motion as float)",
"sharpness": "cast(stats.sharpness as float)",
"exposure": "cast(stats.exposure as float)",
"framing": "cast(stats.framing as float)",
}
)
# --8<-- [end:quickstart_flatten_stats]
def test_quickstart_derived_feature_on_a_deployment(deployment):
# Functions need LanceDB Enterprise: LanceDB Embedded has no Function catalog.
table = create_frames(deployment)
flatten_stats(table)
db = deployment.db
# --8<-- [start:quickstart_add_feature]
from lancedb import col, function
@function
def quality_score(
motion: float, sharpness: float, exposure: float, framing: float
) -> float:
return (motion + sharpness + exposure + framing) / 4.0
version = db.create_function_async(quality_score).wait()
table.add_columns(
{
"quality_score": version(
motion=col("motion"),
sharpness=col("sharpness"),
exposure=col("exposure"),
framing=col("framing"),
)
}
)
job = table.refresh_column_async("quality_score")
job.wait()
# --8<-- [end:quickstart_add_feature]
# --8<-- [start:quickstart_query_feature]
features = (
table.search().select(["frame_id", "video_id", "quality_score"]).to_polars()
)
print(features)
# --8<-- [end:quickstart_query_feature]
assert quality_scores(table) == EXPECTED_QUALITY_SCORES
# The blocking form raises on Enterprise, which is why the snippet uses a job.
with pytest.raises(NotImplementedError, match="refresh_column_async"):
table.refresh_column("quality_score")
def test_quickstart_multimodal(db, tmp_path, monkeypatch):
app = tmp_path / "app"
(app / "data").mkdir(parents=True)
shutil.copy(IMAGE, app / "data/sample-frame.jpg")
monkeypatch.chdir(app)
# --8<-- [start:quickstart_multimodal_bytes]
from pathlib import Path
image_bytes = Path("data/sample-frame.jpg").read_bytes()
multimodal_table = db.create_table(
"frame_images",
data=[
{
"frame_id": "thumb-1",
"caption": "Sample frame thumbnail",
"image": image_bytes,
"embedding": [0.9, 0.1, 0.5, 0.4],
}
],
mode="overwrite",
)
# --8<-- [end:quickstart_multimodal_bytes]
assert multimodal_table.count_rows() == 1
stored = multimodal_table.search().select(["image"]).to_list()[0]["image"]
assert stored == IMAGE.read_bytes()
def test_quickstart_training(db):
table = create_frames(db)
# The real walkthrough reaches this step with motion/sharpness already
# added back in flatten_stats(); add them here too so this test stands
# on its own, without repeating the add_columns call the snippet shows.
flatten_stats(table)
# --8<-- [start:quickstart_training]
import torch
from lancedb.streaming import StreamingDataset
dataset = StreamingDataset(table, columns=["motion", "sharpness"], shuffle_seed=42)
dataloader = torch.utils.data.DataLoader(dataset, batch_size=1024, num_workers=0)
# --8<-- [end:quickstart_training]
batches = list(dataloader)
assert len(batches) == 1
assert set(batches[0]) == {"motion", "sharpness"}
assert all(isinstance(value, torch.Tensor) for value in batches[0].values())
assert sorted(batches[0]["motion"].tolist()) == [2.0, 3.0, 5.0, 5.0]