|
| 1 | +import multiprocessing as mp |
| 2 | +from collections.abc import Iterator |
| 3 | +from concurrent.futures import ProcessPoolExecutor |
| 4 | +from copy import deepcopy |
| 5 | +from pathlib import Path |
| 6 | + |
| 7 | +import pandas as pd |
| 8 | +import pytest |
| 9 | + |
| 10 | +pytest.importorskip("duckdb") |
| 11 | + |
| 12 | +from vectordb_bench import config |
| 13 | +from vectordb_bench.backend.clients.api import MetricType |
| 14 | +from vectordb_bench.backend.clients.duckdb.config import DuckDBConfig, DuckDBIndexConfig |
| 15 | +from vectordb_bench.backend.clients.duckdb.duckdb import DuckDB |
| 16 | +from vectordb_bench.backend.filter import non_filter |
| 17 | +from vectordb_bench.backend.runner.concurrent_runner import ConcurrentInsertRunner |
| 18 | +from vectordb_bench.backend.runner.rate_runner import RatedMultiThreadingInsertRunner |
| 19 | + |
| 20 | + |
| 21 | +class SingleBatchDataset: |
| 22 | + class Fields: |
| 23 | + train_id_field = "id" |
| 24 | + train_vector_field = "emb" |
| 25 | + scalar_labels_file_separated = False |
| 26 | + |
| 27 | + data = Fields() |
| 28 | + |
| 29 | + def iter_batches(self, batch_size: int) -> Iterator[pd.DataFrame]: |
| 30 | + del batch_size |
| 31 | + yield pd.DataFrame( |
| 32 | + { |
| 33 | + "id": [40, 10, 30, 20], |
| 34 | + "emb": [ |
| 35 | + [10.0, 0.0, 0.0], |
| 36 | + [0.0, 1.0, 0.0], |
| 37 | + [0.8, 0.2, 0.0], |
| 38 | + [-1.0, 0.0, 0.0], |
| 39 | + ], |
| 40 | + } |
| 41 | + ) |
| 42 | + |
| 43 | + |
| 44 | +class StreamingDataset: |
| 45 | + def __init__(self) -> None: |
| 46 | + self.batch_index = 0 |
| 47 | + |
| 48 | + def __iter__(self) -> "StreamingDataset": |
| 49 | + return self |
| 50 | + |
| 51 | + def __next__(self) -> pd.DataFrame: |
| 52 | + if self.batch_index == 4: |
| 53 | + raise StopIteration |
| 54 | + start = self.batch_index * config.NUM_PER_BATCH |
| 55 | + self.batch_index += 1 |
| 56 | + return pd.DataFrame( |
| 57 | + { |
| 58 | + "id": list(range(start, start + config.NUM_PER_BATCH)), |
| 59 | + "emb": [[1.0, 0.0, 0.0]] * config.NUM_PER_BATCH, |
| 60 | + } |
| 61 | + ) |
| 62 | + |
| 63 | + |
| 64 | +def make_client( |
| 65 | + path: Path, |
| 66 | + drop_old: bool = True, |
| 67 | + metric_type: MetricType = MetricType.COSINE, |
| 68 | +) -> DuckDB: |
| 69 | + return DuckDB( |
| 70 | + dim=3, |
| 71 | + db_config=DuckDBConfig(db_path=str(path)).to_dict(), |
| 72 | + db_case_config=DuckDBIndexConfig(metric_type=metric_type), |
| 73 | + drop_old=drop_old, |
| 74 | + ) |
| 75 | + |
| 76 | + |
| 77 | +def search_in_process(client: DuckDB, query: list[float], k: int) -> list[int]: |
| 78 | + client.prepare_filter(non_filter) |
| 79 | + with client.init(): |
| 80 | + return client.search_embedding(query, k=k) |
| 81 | + |
| 82 | + |
| 83 | +@pytest.mark.parametrize( |
| 84 | + ("metric_type", "expected"), |
| 85 | + [ |
| 86 | + (MetricType.COSINE, [40, 30, 10]), |
| 87 | + (MetricType.L2, [30, 10, 20]), |
| 88 | + (MetricType.IP, [40, 30, 10]), |
| 89 | + (MetricType.DP, [40, 30, 10]), |
| 90 | + ], |
| 91 | +) |
| 92 | +def test_duckdb_exact_search_reopens_after_copy_round_trip( |
| 93 | + tmp_path: Path, |
| 94 | + metric_type: MetricType, |
| 95 | + expected: list[int], |
| 96 | +) -> None: |
| 97 | + client = make_client(tmp_path / "vectors.duckdb", metric_type=metric_type) |
| 98 | + dataset = SingleBatchDataset() |
| 99 | + batch = next(dataset.iter_batches(4)) |
| 100 | + |
| 101 | + with client.init(): |
| 102 | + count, error = client.insert_embeddings(batch["emb"].tolist(), batch["id"].tolist()) |
| 103 | + |
| 104 | + assert error is None |
| 105 | + assert count == 4 |
| 106 | + |
| 107 | + client = deepcopy(client) |
| 108 | + with client.init(): |
| 109 | + assert client.search_embedding([1.0, 0.0, 0.0], k=3) == expected |
| 110 | + |
| 111 | + |
| 112 | +def test_duckdb_loads_through_concurrent_runner(tmp_path: Path) -> None: |
| 113 | + client = make_client(tmp_path / "runner.duckdb") |
| 114 | + runner = ConcurrentInsertRunner( |
| 115 | + db=client, |
| 116 | + dataset=SingleBatchDataset(), |
| 117 | + normalize=False, |
| 118 | + max_workers=4, |
| 119 | + ) |
| 120 | + |
| 121 | + assert runner.max_workers == 1 |
| 122 | + assert runner.task() == 4 |
| 123 | + |
| 124 | + with client.init(): |
| 125 | + assert client.search_embedding([1.0, 0.0, 0.0], k=2) == [40, 30] |
| 126 | + |
| 127 | + |
| 128 | +def test_duckdb_rolls_back_failed_load(tmp_path: Path) -> None: |
| 129 | + client = make_client(tmp_path / "rollback.duckdb") |
| 130 | + |
| 131 | + def abort_load() -> None: |
| 132 | + with client.init(): |
| 133 | + count, error = client.insert_embeddings([[1.0, 0.0, 0.0]], [1]) |
| 134 | + assert error is None |
| 135 | + assert count == 1 |
| 136 | + raise RuntimeError("abort load") |
| 137 | + |
| 138 | + with pytest.raises(RuntimeError, match="abort load"): |
| 139 | + abort_load() |
| 140 | + |
| 141 | + with client.init(): |
| 142 | + assert client.search_embedding([1.0, 0.0, 0.0], k=1) == [] |
| 143 | + |
| 144 | + |
| 145 | +def test_duckdb_serializes_streaming_insert_threads(tmp_path: Path) -> None: |
| 146 | + client = make_client(tmp_path / "streaming.duckdb") |
| 147 | + runner = RatedMultiThreadingInsertRunner( |
| 148 | + rate=config.NUM_PER_BATCH * 4, |
| 149 | + db=client, |
| 150 | + dataset_iter=StreamingDataset(), |
| 151 | + ) |
| 152 | + queue = mp.Queue() |
| 153 | + |
| 154 | + try: |
| 155 | + runner.run_with_rate(queue) |
| 156 | + finally: |
| 157 | + queue.close() |
| 158 | + queue.join_thread() |
| 159 | + |
| 160 | + expected_ids = set(range(config.NUM_PER_BATCH * 4)) |
| 161 | + with client.init(): |
| 162 | + assert set(client.search_embedding([1.0, 0.0, 0.0], k=len(expected_ids))) == expected_ids |
| 163 | + |
| 164 | + |
| 165 | +def test_duckdb_supports_spawned_concurrent_searches(tmp_path: Path) -> None: |
| 166 | + client = make_client(tmp_path / "concurrent.duckdb") |
| 167 | + dataset = SingleBatchDataset() |
| 168 | + batch = next(dataset.iter_batches(4)) |
| 169 | + with client.init(): |
| 170 | + count, error = client.insert_embeddings(batch["emb"].tolist(), batch["id"].tolist()) |
| 171 | + |
| 172 | + assert error is None |
| 173 | + assert count == 4 |
| 174 | + |
| 175 | + context = mp.get_context("spawn") |
| 176 | + with ProcessPoolExecutor(max_workers=2, mp_context=context) as executor: |
| 177 | + futures = [executor.submit(search_in_process, client, [1.0, 0.0, 0.0], 2) for _ in range(2)] |
| 178 | + |
| 179 | + assert [future.result() for future in futures] == [[40, 30], [40, 30]] |
0 commit comments