mirror of
https://github.com/lancedb/lancedb.git
synced 2026-10-12 14:52:26 +00:00
## Summary
Materialize a source-preserving dedup result from an indexed, pinned
snapshot with a short declaration. The default greedy policy keeps the
smallest unassigned snapshot row ID and removes only its directly
matching neighbors: For A < B < C, an A–B–C chain without an A–C edge
keeps A and C.
```python
from lancedb import vector_dedup
view = db.create_materialized_view(
"images_clean",
vector_dedup("images", column="phash", distance_threshold=4),
)
cleaned = view.table
```
The Python source expression captures the source version once at
creation and
waits for the materialized result by default. Use `dataset_version=...`
for an
explicit snapshot, `with_no_data=True` for declaration only, or
`create_materialized_view_async(...)` for a job handle. AsyncConnection
supports
the same expression. It uses the existing MV REST endpoints and registry
jobs,
without opening a SQL query connection. Source names are exact
root-namespace
table names. Additional select/where/limit options are rejected for this
source.
The SQL declaration remains available:
```sql
CREATE MATERIALIZED VIEW images_clean AS
SELECT * FROM vector_dedup('images', 7, 'phash', 4);
REFRESH MATERIALIZED VIEW images_clean;
```
This is the host-facing SQL entry point. The MV builder now accepts a
typed native vector source; the Rust SDK also supports the same
definition through `MaterializedViewDefinition::from_sql` and
`prepare_definition`; `view.refresh().execute()` executes it locally.
Hosts distribute its units using their existing job infrastructure. The
raw `vector_duplicate_pairs` source remains available separately when
callers want the pair relation.
## Implementation and contract
- Use actual Rust Lance `13.0.0-beta.15` (`db53dcf367`); the native
partition primitive computes pairs from index representations without
source-vector aggregation or a Python pair loop.
- Extend partitioned MV refresh with two dependent waves. Physical
segment/partition tasks stream pairs through a bounded external sort,
select direct representatives and write per-source-fragment bitmap
artifacts. Source-fragment tasks start after every selection receipt
completes and stream retained original rows, including blob payloads,
into uncommitted output fragments.
- Reuse normal blob write coercion and row-mask scans, including stable
row-ID translation after compaction. Null vectors, isolated rows and
source deletions are preserved correctly. Conflicting representative
decisions across overlapping index scopes fail before publication.
- Expose `dependency_units()` and `write_refresh_partition_with_inputs`
alongside the existing plan/commit API. Receipts bind
snapshot/configuration/policy/destination generation. Only a complete
accepted set can publish; unfinished units restart, completed units can
be reused. There is no pair-position checkpoint.
- Use MV format 4 for dedup results and format 3 for native pairs;
Python and TypeScript metadata readers recognize both. No source
deletion or source row-ID migration occurs.
Only same-segment/same-partition edges are covered. Quantized scores use
symmetric represented-vector distances. Result materialization requires
V2 data storage and is initially a native MV source, not an ordinary
SELECT table function. Compressed vertex masks stay in memory; edge
sorting spills to local disk. Unreferenced artifacts use normal Lance
retention/cleanup and must be retained for the job's recovery window.
## Validation
AWS Linux validation:
- Native pair/result integration matrix passed: multiple
segments/partitions, exact thresholds, empty output, cross-batch data,
single-process pair parity, source preservation, lost receipts and
publication guards.
- Blob/null-vector/pinned-deletion tests passed with both row-ID modes,
including compaction that changes physical row addresses.
- Representative policy, forced external-sort spill and
conflicting/corrupt artifact tests passed.
- Full MV regression suite: 153 passed, 2 pre-existing ignored. Rust
formatting and Clippy passed.
- Python MV suite: 47 passed; TypeScript MV suite: 11 passed. Native
bindings were rebuilt in project-local environments; formatting, lint
and TypeScript docs passed.
- Rust declaration doctests: 3 passed, including the complete local
dedup example.
- Companion host validation: 41 MV job tests passed (1 pre-existing
ignored), full workspace Clippy passed, and the complete process-level
CLI E2E suite passed (3 tests). Recovery exercises both selection and
materialization waves.
- A real CIFAR-10 pHash run used five actual registry-worker owners,
completed 32 selection + 24 materialization tasks, and retained 49,846
of 50,000 rows with identical original values and image payloads.
Host workflow performance measurements are recorded in the companion
host PR. Cross-platform CI is still running. The previous remote-test
bootstrap failed before Cargo tests with `401 Bad credentials`; the
workflow fix described below is being validated by CI. No deployment or
merge is performed.
## Python source validation
AWS tests cover automatic and explicit snapshots, physical/stable row
IDs, local
and remote creation, sync/job/async-connection APIs, delayed refresh,
strict
options and identifier quoting. The native Python extension was rebuilt
through
the project's uv/maturin backend. Ruff, Pyright and the full MkDocs
API-reference
build passed; both new public symbols are rendered.
A real 50,000-image FEv2 run disabled both Python SQL entry points and
supplied an
unreachable SQL endpoint. The new API still materialized the same 49,846
retained
rows and original image payloads. Three recorded creation/refresh jobs
completed
56 tasks each on all five registry-worker owners, and remained on source
snapshot
3 after source latest advanced to 4. No worker or server wire-protocol
changes
were needed for this client entry point.
Previous CI authentication failure:
https://github.com/lancedb/lancedb/actions/runs/36334679276/job/108663151265.
## Review and CI fixes
- Validate all JSON merge source fields before projection, rejecting
unknown and duplicate names at every struct level. Missing/reordered
fields and ordinary JSON merges remain supported. A checked-in 12-case
integration matrix covers root fields, structs, lists, large lists,
fixed-size lists and map values; rejected writes leave the table version
and row count unchanged.
- Match namespace connection MV method signatures to
`MaterializedViewSource` in all four sync/async methods, fixing the
Python 3.10 import failure from runtime override checks.
- Restore the remote-test script's encrypted-CLI path: use the Actions
token for artifact download and pass `SOPHON_READ_TOKEN` under the
variable the decryption script consumes. The previous workflow omitted
that variable and attempted the private release path, failing with HTTP
401. On the final head, remote CI passes: 1,464 Rust unit tests, the
integration targets and doctests pass (3 unit tests ignored).
AWS validation for these fixes: both review reproducers failed before
their fixes and pass afterward; 55 merge tests, 29 cast tests and the
standalone 7-case admission regression pass. Python 3.10.21 imports
successfully; 90 MV/namespace tests, 14 JSON tests and four real
namespace dedup cases pass. After `794b97a0`, the native binding was
rebuilt again and the JSON suite rerun. Rust formatting/Clippy, Ruff and
Pyright pass. Sophon's locked test compilation passes against the final
SDK source for all seven affected crates. Extended runners, logs and
benchmark artifacts remain local.
Gatekeeper recommends approval on `794b97a0`, and the `breaking-change`
label is set. Final CI: **49 checks passed, 3 expected skips, no
failures or pending checks**, including remote tests, Python 3.10,
minimum dependencies and Windows ARM Rust tests. All wheel builds pass
after retrying the Linux matrix affected by transient AlmaLinux
repository-metadata 404s. All code-review threads are resolved. The PR
remains open for maintainer review and merge.
---------
Co-authored-by: Yang Cen <yangcen@Yangs-Mac-mini.local>
Co-authored-by: Lance Release <lance-dev@lancedb.com>
193 lines
6.1 KiB
TypeScript
193 lines
6.1 KiB
TypeScript
// SPDX-License-Identifier: Apache-2.0
|
|
// SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
|
|
|
import * as tmp from "tmp";
|
|
|
|
import { Connection, connect } from "../lancedb";
|
|
import {
|
|
DEFINITION_META_KEY,
|
|
definitionFromMetadata,
|
|
} from "../lancedb/materialized_view";
|
|
|
|
describe("materialized views", () => {
|
|
let tmpDir: tmp.DirResult;
|
|
let db: Connection;
|
|
|
|
beforeEach(async () => {
|
|
tmpDir = tmp.dirSync({ unsafeCleanup: true });
|
|
db = await connect(tmpDir.name);
|
|
await db.createTable(
|
|
"people",
|
|
[
|
|
{ name: "ada", age: 36 },
|
|
{ name: "kid", age: 7 },
|
|
{ name: "grace", age: 85 },
|
|
],
|
|
{ storageOptions: { newTableEnableStableRowIds: "true" } },
|
|
);
|
|
});
|
|
afterEach(() => tmpDir.removeCallback());
|
|
|
|
it("reads stored queries and legacy layouts", () => {
|
|
const read = (stored: string) =>
|
|
definitionFromMetadata(new Map([[DEFINITION_META_KEY, stored]]), "v");
|
|
const query =
|
|
"SELECT id, c.chunk FROM ns.docs, UNNEST(chunks) AS c WHERE id > 1";
|
|
expect(read(`{"format":1,"query":${JSON.stringify(query)}}`).query).toBe(
|
|
query,
|
|
);
|
|
|
|
// The structured layout written before the format number reads as the
|
|
// query it described, under either of its kind tags.
|
|
expect(
|
|
read(
|
|
'{"kind":"namespaced_select","source_table":"people","source_namespace":["ns"],' +
|
|
'"projections":[{"output":"name","expression":"`name`"},' +
|
|
'{"output":"Shout","expression":"upper(name)"}],"filter":"age >= 18","limit":42}',
|
|
).query,
|
|
).toBe(
|
|
"SELECT `name`, upper(name) AS `Shout` FROM ns.people WHERE age >= 18 LIMIT 42",
|
|
);
|
|
expect(read('{"kind":"select","source_table":"people"}').query).toBe(
|
|
"SELECT * FROM people",
|
|
);
|
|
|
|
for (const [format, fn] of [
|
|
[3, "vector_duplicate_pairs"],
|
|
[4, "vector_dedup"],
|
|
]) {
|
|
const native = `SELECT * FROM ${fn}('images', 3, 'phash', 4)`;
|
|
expect(read(JSON.stringify({ format, query: native })).query).toBe(
|
|
native,
|
|
);
|
|
}
|
|
|
|
// A newer writer's layout is reported, never guessed at.
|
|
for (const newer of [
|
|
`{"format":5,"query":${JSON.stringify(query)}}`,
|
|
'{"kind":"select_v3","source_table":"people"}',
|
|
]) {
|
|
expect(() => read(newer)).toThrow(/cannot refresh/);
|
|
}
|
|
});
|
|
|
|
it("rejects a stored limit a number cannot carry", () => {
|
|
const big = new Map([
|
|
[
|
|
DEFINITION_META_KEY,
|
|
'{"kind":"select","source_table":"people","limit":9007199254740993}',
|
|
],
|
|
]);
|
|
expect(() => definitionFromMetadata(big, "v")).toThrow(
|
|
/too large to represent exactly/,
|
|
);
|
|
});
|
|
|
|
it("creates, refreshes and queries a view", async () => {
|
|
const view = await db.createMaterializedView("adults", "people", {
|
|
select: ["name", ["shout", "upper(name)"]],
|
|
where: "age >= 18",
|
|
});
|
|
expect(view.name).toBe("adults");
|
|
expect(await view.table().countRows()).toBe(2);
|
|
|
|
const rows = await view.table().query().toArray();
|
|
expect(rows.map((r) => r.shout).sort()).toEqual(["ADA", "GRACE"]);
|
|
});
|
|
|
|
it("round-trips the definition", async () => {
|
|
await db.createMaterializedView("adults", "people", {
|
|
where: "age >= 18",
|
|
});
|
|
const view = await db.openMaterializedView("adults");
|
|
const definition = await view.definition();
|
|
expect(definition.query).toBe(
|
|
"SELECT name, age FROM people WHERE age >= 18",
|
|
);
|
|
});
|
|
|
|
it("refreshes incrementally after an append", async () => {
|
|
const view = await db.createMaterializedView("copy", "people", {
|
|
withNoData: true,
|
|
});
|
|
await view.refresh();
|
|
|
|
const people = await db.openTable("people");
|
|
await people.add([{ name: "alan", age: 41 }]);
|
|
const result = await view.refresh();
|
|
expect(result.mode).toBe("incremental");
|
|
expect(Number(result.rowsWritten)).toBe(1);
|
|
expect(await view.table().countRows()).toBe(4);
|
|
|
|
expect((await view.refresh()).mode).toBe("no_op");
|
|
});
|
|
|
|
it("lists views and rejects non-views", async () => {
|
|
await db.createMaterializedView("adults", "people", {
|
|
where: "age >= 18",
|
|
});
|
|
expect(await db.listMaterializedViews()).toEqual(["adults"]);
|
|
await expect(db.openMaterializedView("people")).rejects.toThrow(
|
|
"not a materialized view",
|
|
);
|
|
await expect(db.dropMaterializedView("people")).rejects.toThrow(
|
|
"not a materialized view",
|
|
);
|
|
|
|
await db.dropMaterializedView("adults");
|
|
expect(await db.listMaterializedViews()).toEqual([]);
|
|
});
|
|
|
|
it("returns a job when dropping a view asynchronously", async () => {
|
|
await db.createMaterializedView("adults", "people");
|
|
|
|
const job = await db.dropMaterializedViewAsync("adults");
|
|
expect(job.id).toBeNull();
|
|
await job.wait();
|
|
expect(await db.listMaterializedViews()).toEqual([]);
|
|
});
|
|
|
|
it("rejects an invalid expression at create time", async () => {
|
|
await expect(
|
|
db.createMaterializedView("bad", "people", {
|
|
select: [["x", "missing + 1"]],
|
|
}),
|
|
).rejects.toThrow("missing");
|
|
});
|
|
|
|
it("rejects invalid numeric options before creating anything", async () => {
|
|
for (const limit of [-5, 1.5, Infinity, NaN]) {
|
|
await expect(
|
|
db.createMaterializedView("bad", "people", { limit }),
|
|
).rejects.toThrow("non-negative integer");
|
|
}
|
|
expect(await db.listMaterializedViews()).toEqual([]);
|
|
|
|
const view = await db.createMaterializedView("copy", "people");
|
|
for (const sourceVersion of [-1, 1.5, Infinity, NaN]) {
|
|
await expect(view.refresh({ sourceVersion })).rejects.toThrow(
|
|
"non-negative integer",
|
|
);
|
|
}
|
|
});
|
|
|
|
it("quotes bare select names", async () => {
|
|
await db.createTable("odd_names", [{ "order item": "widget" }], {
|
|
storageOptions: { newTableEnableStableRowIds: "true" },
|
|
});
|
|
const view = await db.createMaterializedView("quoted", "odd_names", {
|
|
select: ["order item"],
|
|
withNoData: true,
|
|
});
|
|
const result = await view.refresh();
|
|
expect(Number(result.rowsWritten)).toBe(1);
|
|
});
|
|
|
|
it("requires stable row ids on the source", async () => {
|
|
await db.createTable("plain", [{ x: 1 }]);
|
|
await expect(db.createMaterializedView("v", "plain")).rejects.toThrow(
|
|
"stable row ids",
|
|
);
|
|
});
|
|
});
|