mirror of
https://github.com/lancedb/lancedb.git
synced 2026-12-03 15:55:19 +00:00
Add rerank_vector() and rerank_fts() methods to Reranker trait, allowing rerankers to work with single search modes instead of only hybrid search. Implemented for: - RRFReranker (Rust and Python) - LinearCombinationReranker (Python) Resolves TODO at rust/lancedb/src/rerankers.rs:55 Changes: - Extended Reranker trait with default implementations - Added unit tests for new methods - Updated documentation with examples --------- Co-authored-by: Xuanwo <github@xuanwo.io>
314 lines
9.6 KiB
TypeScript
314 lines
9.6 KiB
TypeScript
// SPDX-License-Identifier: Apache-2.0
|
|
// SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
|
|
|
import { execFileSync, spawn } from "node:child_process";
|
|
import * as path from "node:path";
|
|
import { Field, Float64, RecordBatch, Schema } from "apache-arrow";
|
|
import * as tmp from "tmp";
|
|
import { Connection, Index, Table, connect, makeArrowTable } from "../lancedb";
|
|
import { RRFReranker } from "../lancedb/rerankers";
|
|
|
|
it("reranks record batches created by an ESM Arrow import", () => {
|
|
const script = `
|
|
import assert from "node:assert/strict";
|
|
import { tableFromArrays } from "apache-arrow";
|
|
import { rerankers } from "./dist/index.js";
|
|
|
|
const ids = [1n, 9007199254740993n];
|
|
const batch = tableFromArrays({ _rowid: new BigUint64Array(ids) }).batches[0];
|
|
const reranker = await rerankers.RRFReranker.create();
|
|
const result = await reranker.rerankHybrid("", batch, batch);
|
|
|
|
assert.equal(result.numRows, 2);
|
|
assert.deepEqual(Array.from(result.getChild("_rowid").toArray()), ids);
|
|
const scores = result.getChild("_relevance_score").toArray();
|
|
assert.ok(Math.abs(scores[0] - 2 / 61) < 1e-8);
|
|
assert.ok(Math.abs(scores[1] - 2 / 62) < 1e-8);
|
|
|
|
const oneSide = await reranker.rerankHybrid("", batch, batch.slice(0, 0));
|
|
assert.deepEqual(Array.from(oneSide.getChild("_rowid").toArray()), ids);
|
|
const oneSideScores = oneSide.getChild("_relevance_score").toArray();
|
|
assert.ok(Math.abs(oneSideScores[0] - 1 / 61) < 1e-8);
|
|
assert.ok(Math.abs(oneSideScores[1] - 1 / 62) < 1e-8);
|
|
`;
|
|
execFileSync(process.execPath, ["--input-type=module", "-e", script], {
|
|
cwd: path.resolve(__dirname, ".."),
|
|
timeout: 10_000,
|
|
});
|
|
});
|
|
|
|
describe("rerankers", function () {
|
|
let tmpDir: tmp.DirResult;
|
|
let conn: Connection;
|
|
let table: Table;
|
|
|
|
beforeEach(async () => {
|
|
tmpDir = tmp.dirSync({ unsafeCleanup: true });
|
|
conn = await connect(tmpDir.name);
|
|
table = await conn.createTable("mytable", [
|
|
{ vector: [0.1, 0.1], text: "dog" },
|
|
{ vector: [0.2, 0.2], text: "cat" },
|
|
]);
|
|
await table.createIndex("text", {
|
|
config: Index.fts(),
|
|
replace: true,
|
|
});
|
|
});
|
|
|
|
it("will query with the custom reranker", async function () {
|
|
const expectedResult = [
|
|
{
|
|
text: "albert",
|
|
// biome-ignore lint/style/useNamingConvention: this is the lance field name
|
|
_relevance_score: 0.99,
|
|
},
|
|
];
|
|
class MyCustomReranker {
|
|
async rerankHybrid(
|
|
_query: string,
|
|
_vecResults: RecordBatch,
|
|
_ftsResults: RecordBatch,
|
|
): Promise<RecordBatch> {
|
|
// no reranker logic, just return some static data
|
|
const table = makeArrowTable(expectedResult);
|
|
return table.batches[0];
|
|
}
|
|
}
|
|
|
|
let result = await table
|
|
.query()
|
|
.nearestTo([0.1, 0.1])
|
|
.fullTextSearch("dog")
|
|
.rerank(new MyCustomReranker())
|
|
.select(["text"])
|
|
.limit(5)
|
|
.toArray();
|
|
|
|
result = JSON.parse(JSON.stringify(result)); // convert StructRow to Object
|
|
expect(result).toEqual([
|
|
{
|
|
text: "albert",
|
|
// biome-ignore lint/style/useNamingConvention: this is the lance field name
|
|
_relevance_score: 0.99,
|
|
},
|
|
]);
|
|
});
|
|
|
|
it("will query with RRFReranker", async function () {
|
|
// smoke test to see if the Rust wrapping Typescript is wired up correctly
|
|
const result = await table
|
|
.query()
|
|
.nearestTo([0.1, 0.1])
|
|
.fullTextSearch("dog")
|
|
.rerank(await RRFReranker.create())
|
|
.select(["text"])
|
|
.limit(5)
|
|
.toArray();
|
|
|
|
expect(result).toHaveLength(2);
|
|
});
|
|
|
|
it("returns one-based RRF scores and the declared vector query schema", async function () {
|
|
const query = table
|
|
.vectorSearch([0.1, 0.1])
|
|
.limit(2)
|
|
.select(["text"])
|
|
.rerank(await RRFReranker.create());
|
|
const schema = await query.outputSchema();
|
|
const result = await query.toArrow();
|
|
|
|
expect(result.schema.fields).toEqual(schema.fields);
|
|
expect(schema.fields.map((field) => field.name)).toEqual([
|
|
"text",
|
|
"_distance",
|
|
"_relevance_score",
|
|
]);
|
|
expect(result.getChild("text")?.toArray()).toEqual(["dog", "cat"]);
|
|
const scores = result.getChild("_relevance_score")?.toArray();
|
|
expect(scores?.[0]).toBeCloseTo(1 / 61, 8);
|
|
expect(scores?.[1]).toBeCloseTo(1 / 62, 8);
|
|
});
|
|
|
|
it("preserves the reranked schema for an empty vector result", async function () {
|
|
const query = table
|
|
.vectorSearch([0.1, 0.1])
|
|
.where("text = 'absent'")
|
|
.withRowId()
|
|
.rerank(await RRFReranker.create());
|
|
const schema = await query.outputSchema();
|
|
const result = await query.toArrow();
|
|
|
|
expect(result.numRows).toBe(0);
|
|
expect(result.schema.fields).toEqual(schema.fields);
|
|
expect(result.schema.fields.map((field) => field.name)).toEqual(
|
|
expect.arrayContaining(["_rowid", "_relevance_score"]),
|
|
);
|
|
});
|
|
|
|
it("dispatches to a custom vector callback with its declared output fields", async function () {
|
|
const rerankedScore = 0.75;
|
|
const declared = new Schema([
|
|
new Field("_relevance_score", new Float64(), false),
|
|
]);
|
|
const rerankVector = jest.fn(
|
|
async (_query: string, results: RecordBatch) => {
|
|
expect(results.numRows).toBe(2);
|
|
return makeArrowTable(
|
|
// biome-ignore lint/style/useNamingConvention: this is the lance field name
|
|
[{ _relevance_score: rerankedScore }],
|
|
{ schema: declared },
|
|
).batches[0];
|
|
},
|
|
);
|
|
const rerankHybrid = jest.fn(async () => {
|
|
throw new Error("unexpected hybrid callback");
|
|
});
|
|
const query = table
|
|
.vectorSearch([0.1, 0.1])
|
|
.limit(2)
|
|
.rerank({
|
|
rerankVector,
|
|
rerankHybrid,
|
|
outputSchema: () => declared,
|
|
});
|
|
expect((await query.outputSchema()).fields).toEqual(declared.fields);
|
|
expect(rerankVector).not.toHaveBeenCalled();
|
|
const result = await query.toArrow();
|
|
expect(result.getChild("_relevance_score")?.toArray()).toEqual(
|
|
new Float64Array([rerankedScore]),
|
|
);
|
|
expect(rerankVector).toHaveBeenCalledTimes(1);
|
|
expect(rerankHybrid).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("reports a rejected rerankVector callback to the query caller", async function () {
|
|
const rerankVector = jest.fn(async () => {
|
|
throw new Error("vector scoring failed");
|
|
});
|
|
const rerankHybrid = jest.fn(async () => {
|
|
throw new Error("unexpected hybrid callback");
|
|
});
|
|
const query = table
|
|
.vectorSearch([0.1, 0.1])
|
|
.rerank({ rerankVector, rerankHybrid });
|
|
|
|
await expect(query.toArrow()).rejects.toThrow("vector scoring failed");
|
|
expect(rerankVector).toHaveBeenCalledTimes(1);
|
|
expect(rerankHybrid).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("applies the query timeout while rerankVector is pending", async function () {
|
|
let rejectPending: ((error: Error) => void) | undefined;
|
|
const rerankVector = jest.fn(
|
|
() =>
|
|
new Promise<RecordBatch>((_resolve, reject) => {
|
|
rejectPending = reject;
|
|
}),
|
|
);
|
|
const rerankHybrid = jest.fn(async () => {
|
|
throw new Error("unexpected hybrid callback");
|
|
});
|
|
const query = table
|
|
.vectorSearch([0.1, 0.1])
|
|
.rerank({ rerankVector, rerankHybrid });
|
|
|
|
try {
|
|
await expect(query.toArrow({ timeoutMs: 500 })).rejects.toThrow(
|
|
"Query timeout after 500 ms",
|
|
);
|
|
expect(rerankVector).toHaveBeenCalledTimes(1);
|
|
expect(rerankHybrid).not.toHaveBeenCalled();
|
|
} finally {
|
|
rejectPending?.(new Error("callback rejected after query timeout"));
|
|
}
|
|
await new Promise<void>((resolve) => setImmediate(resolve));
|
|
});
|
|
|
|
it("does not keep process alive after rerank query", async function () {
|
|
const script = `
|
|
import * as lancedb from "./dist/index.js";
|
|
import * as os from "node:os";
|
|
import * as path from "node:path";
|
|
import * as fs from "node:fs/promises";
|
|
|
|
const dir = await fs.mkdtemp(path.join(os.tmpdir(), "lancedb-rerank-exit-"));
|
|
const db = await lancedb.connect(dir);
|
|
const table = await db.createTable("test", [{ text: "hello", vector: [1, 2, 3] }], {
|
|
mode: "overwrite",
|
|
});
|
|
await table.createIndex("text", { config: lancedb.Index.fts() });
|
|
await table.waitForIndex(["text_idx"], 30);
|
|
|
|
const reranker = await lancedb.rerankers.RRFReranker.create();
|
|
await table
|
|
.query()
|
|
.nearestTo([1, 2, 3])
|
|
.fullTextSearch("hello")
|
|
.rerank(reranker)
|
|
.toArray();
|
|
|
|
table.close();
|
|
db.close();
|
|
`;
|
|
|
|
await new Promise<void>((resolve, reject) => {
|
|
const child = spawn(
|
|
process.execPath,
|
|
["--input-type=module", "-e", script],
|
|
{
|
|
cwd: path.resolve(__dirname, ".."),
|
|
stdio: ["ignore", "pipe", "pipe"],
|
|
},
|
|
);
|
|
|
|
let stdout = "";
|
|
let stderr = "";
|
|
|
|
child.stdout.on("data", (chunk) => {
|
|
stdout += chunk.toString();
|
|
});
|
|
|
|
child.stderr.on("data", (chunk) => {
|
|
stderr += chunk.toString();
|
|
});
|
|
|
|
const timeout = setTimeout(() => {
|
|
child.kill();
|
|
reject(
|
|
new Error(
|
|
`child process did not exit in time\nstdout:\n${stdout}\nstderr:\n${stderr}`,
|
|
),
|
|
);
|
|
}, 20_000);
|
|
|
|
child.on("error", (err) => {
|
|
clearTimeout(timeout);
|
|
reject(err);
|
|
});
|
|
|
|
child.on("exit", (code, signal) => {
|
|
clearTimeout(timeout);
|
|
if (signal !== null) {
|
|
reject(
|
|
new Error(
|
|
`child process exited with signal ${signal}\nstdout:\n${stdout}\nstderr:\n${stderr}`,
|
|
),
|
|
);
|
|
return;
|
|
}
|
|
|
|
if (code !== 0) {
|
|
reject(
|
|
new Error(
|
|
`child process exited with code ${code}\nstdout:\n${stdout}\nstderr:\n${stderr}`,
|
|
),
|
|
);
|
|
return;
|
|
}
|
|
|
|
resolve();
|
|
});
|
|
});
|
|
});
|
|
});
|