scann-core 0.2.1

Rust bindings for scann-core: ScaNN's approximate nearest-neighbour vector search core as a standalone library (derived from Google's ScaNN; not an official Google product)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
// Copyright 2026 The Google Research Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Modified in 2026 by Elias Benali (@ebenali) and TheCleaners for
// scann-core (a derived work of ScaNN, not an official Google product);
// see NOTICE.

#include "scann/scann_ops/cc/scann_npy.h"

#include <algorithm>
#include <atomic>
#include <cmath>
#include <cstdint>
#include <functional>
#include <optional>
#include <stdexcept>
#include <string>
#include <utility>
#include <vector>

#include "absl/strings/str_cat.h"
#include "pybind11/gil.h"
#include "pybind11/pytypes.h"
#include "scann/base/single_machine_base.h"
#include "scann/data_format/datapoint.h"
#include "scann/data_format/dataset.h"
#include "scann/scann_ops/cc/scann.h"
#include "scann/utils/common.h"
#include "scann/utils/io_oss_wrapper.h"
#include "scann/utils/single_machine_autopilot.h"
#include "scann/utils/types.h"

namespace research_scann {
using MutationOptions = UntypedSingleMachineSearcherBase::MutationOptions;
using PrecomputedMutationArtifacts =
    UntypedSingleMachineSearcherBase::PrecomputedMutationArtifacts;

void RuntimeErrorIfNotOk(const char* prefix, const Status& status) {
  if (!status.ok()) {
    std::string msg = prefix + std::string(status.message());
    throw std::runtime_error(msg);
  }
}

template <typename T>
T ValueOrRuntimeError(StatusOr<T> status_or, const char* prefix) {
  RuntimeErrorIfNotOk(prefix, status_or.status());
  return status_or.value();
}

// scann-core: the most datapoints an index can hold. Indices are 32-bit and
// kInvalidDatapointIndex (the largest) is reserved, so the last valid index
// is kInvalidDatapointIndex - 1.
constexpr uint64_t kMaxDatapoints = kInvalidDatapointIndex;

ScannNumpy::ScannNumpy(const std::string& artifacts_dir,
                       const std::string& scann_assets_pbtxt) {
  // scann-core: loading takes seconds for a large index; upstream held the
  // GIL throughout, stalling every Python thread.
  pybind11::gil_scoped_release gil_release;
  auto status_or =
      ScannInterface::LoadArtifacts(artifacts_dir, scann_assets_pbtxt);
  RuntimeErrorIfNotOk("Error loading artifacts: ", status_or.status());
  RuntimeErrorIfNotOk("Error initializing searcher: ",
                      scann_.Initialize(status_or.value()));
}

ScannNumpy::ScannNumpy(const np_row_major_arr<float>& np_dataset,
                       absl::string_view config, int training_threads) {
  if (np_dataset.ndim() != 2)
    throw std::invalid_argument("Dataset input must be two-dimensional");
  // scann-core: datapoint indices are 32-bit. Upstream passed the row count
  // on truncated to 32 bits, building an index over the wrong number of
  // rows (or failing with an unrelated shape error).
  if (static_cast<uint64_t>(np_dataset.shape()[0]) > kMaxDatapoints)
    throw std::invalid_argument(absl::StrCat(
        "Dataset has ", np_dataset.shape()[0], " rows; ScaNN supports at most ",
        kMaxDatapoints, " (datapoint indices are 32-bit)"));
  ConstSpan<float> dataset(np_dataset.data(), np_dataset.size());
  pybind11::gil_scoped_release gil_release;
  RuntimeErrorIfNotOk("Error initializing searcher: ",
                      scann_.Initialize(dataset, np_dataset.shape()[0], config,
                                        training_threads));
}

vector<DatapointIndex> ScannNumpy::Upsert(
    vector<std::optional<DatapointIndex>> indices,
    vector<np_row_major_arr<float>>& vecs, int batch_size) {
  if (batch_size < 1)
    throw std::invalid_argument("Upsert batch_size must be >= 1.");
  pybind11::gil_scoped_release gil_release;
  return UpsertRows(
      indices, vecs.size(),
      [&](size_t row) { return ConstSpan<float>(vecs[row].data(), vecs[row].size()); },
      batch_size);
}

// scann-core: upsert from one row-major 2-D array, read in place with the GIL
// released. The list-of-rows overload above makes pybind11 build one Python
// array object per row, with the GIL held.
vector<DatapointIndex> ScannNumpy::Upsert(
    vector<std::optional<DatapointIndex>> indices,
    const np_row_major_arr<float>& vecs, int batch_size) {
  if (batch_size < 1)
    throw std::invalid_argument("Upsert batch_size must be >= 1.");
  if (vecs.ndim() != 2)
    throw std::invalid_argument("Upsert vectors must be a two-dimensional array");
  const size_t n = vecs.shape()[0];
  const size_t width = vecs.shape()[1];
  const float* data = vecs.data();
  pybind11::gil_scoped_release gil_release;
  return UpsertRows(
      indices, n,
      [&](size_t row) { return ConstSpan<float>(data + row * width, width); },
      batch_size);
}

vector<DatapointIndex> ScannNumpy::UpsertRows(
    const vector<std::optional<DatapointIndex>>& indices, size_t n_rows,
    const std::function<ConstSpan<float>(size_t)>& rows, int batch_size) {
  absl::MutexLock lock(&mu_);
  if (indices.size() != n_rows)
    throw std::runtime_error("Upsert input size must match.");
  // scann-core: validate every row before mutating anything. Upstream
  // checked nothing here: a wrong-sized vector failed deep in the mutator
  // with an uninformative "SCANN_RET_CHECK failure"; a NaN/infinity vector
  // got partition token -1 in tree indexes and the mutator then indexed
  // leaf_mutators_[-1] (segfault); and any row failing partway through a
  // batch left the earlier rows applied, so the index and the caller's docid
  // bookkeeping diverged.
  const DatapointIndex n_points = scann_.n_points();
  const uint64_t n_adds =
      std::count_if(indices.begin(), indices.end(),
                    [](const auto& index) { return !index.has_value(); });
  if (n_points + n_adds > kMaxDatapoints)
    throw std::invalid_argument(absl::StrCat(
        "Upsert would grow the index to ", n_points + n_adds,
        " datapoints; ScaNN supports at most ", kMaxDatapoints,
        " (datapoint indices are 32-bit)"));
  for (size_t row : Seq(n_rows)) {
    const ConstSpan<float> vec = rows(row);
    if (vec.size() != scann_.dimensionality())
      throw std::invalid_argument(absl::StrCat(
          "Upsert vector has dimensionality ", vec.size(),
          ", but the dataset has ", scann_.dimensionality(), " (row ", row,
          ")"));
    for (float v : vec)
      if (!std::isfinite(v))
        throw std::invalid_argument(absl::StrCat(
            "Upsert vector at row ", row,
            " contains NaN or infinity; ScaNN only supports finite values."));
    if (indices[row].has_value() && indices[row].value() >= n_points)
      throw std::invalid_argument(absl::StrCat(
          "Upsert index ", indices[row].value(), " at row ", row,
          " is out of range for an index with ", n_points, " points"));
  }
  auto mutator =
      ValueOrRuntimeError(scann_.GetMutator(), "Failed to fetch mutator: ");
  if (batch_size > 1)
    mutator->set_mutation_threadpool(scann_.parallel_query_pool());

  const DatapointIndex n = n_rows;
  vector<DatapointIndex> result;
  result.reserve(n);

  // scann-core: the vectors as the index stores them: unit vectors with
  // spherical partitioning, with l2_as_dot_product's extra coordinate; see
  // ScannInterface::ToStoredDatapoints.
  const size_t dim = scann_.dimensionality();
  const size_t stored_dim = scann_.stored_dimensionality();
  vector<float> stored;
  if (scann_.TransformsDatapoints()) {
    vector<float> given(n_rows * dim);
    for (size_t row : Seq(n_rows)) {
      const ConstSpan<float> vec = rows(row);
      std::copy(vec.begin(), vec.end(), given.begin() + row * dim);
    }
    scann_.ToStoredDatapoints(given, &stored);
  }
  auto row_ptr = [&](size_t row) {
    return MakeDatapointPtr(stored.empty() ? rows(row).data()
                                           : stored.data() + row * stored_dim,
                            stored_dim);
  };

  for (size_t b : Seq(DivRoundUp(n, batch_size))) {
    size_t begin = batch_size * b;
    size_t bs = std::min<DatapointIndex>(n - begin, batch_size);
    DenseDataset<float> ds;
    for (size_t i : Seq(bs))
      RuntimeErrorIfNotOk("Error appending datapoint.",
                          ds.Append(row_ptr(begin + i)));
    auto precomputed = mutator->ComputePrecomputedMutationArtifacts(
        ds, scann_.parallel_query_pool());

    for (size_t i : Seq(bs)) {
      auto& index = indices[begin + i];
      auto mo = MutationOptions{.precomputed_mutation_artifacts =
                                    precomputed[i].get()};
      if (!index.has_value()) {
        result.push_back(ValueOrRuntimeError(
            mutator->AddDatapoint(row_ptr(begin + i), "", mo),
            "Failed to add datapoint: "));
      } else {
        result.push_back(ValueOrRuntimeError(
            mutator->UpdateDatapoint(row_ptr(begin + i), index.value(), mo),
            "Failed to update datapoint: "));
      }
    }
  }
  // scann-core: incremental maintenance once per call, after every row is
  // in (upstream: after every batch, i.e. after every row with the Python
  // wrapper's batch_size of 1). With autopilot it recomputes the autopilot
  // config each time, and a retrain it triggers midway was redone work.
  auto statusor = mutator->IncrementalMaintenance();
  RuntimeErrorIfNotOk("Error performing incremental maintenance ",
                      statusor.status());
  if (statusor.value().has_value()) RebalanceLocked("");
  return result;
}

vector<DatapointIndex> ScannNumpy::Delete(vector<DatapointIndex> indices) {
  pybind11::gil_scoped_release gil_release;
  absl::MutexLock lock(&mu_);
  auto mutator =
      ValueOrRuntimeError(scann_.GetMutator(), "Failed to fetch mutator: ");
  mutator->set_mutation_threadpool(scann_.parallel_query_pool());
  vector<DatapointIndex> result;
  for (const auto& index : indices) {
    RuntimeErrorIfNotOk("Failed to delete datapoint: ",
                        mutator->RemoveDatapoint(index));
    auto statusor = mutator->IncrementalMaintenance();
    RuntimeErrorIfNotOk("Error performing incremental maintenance ",
                        statusor.status());
    if (statusor.value().has_value()) {
      RebalanceLocked("");
      mutator =
          ValueOrRuntimeError(scann_.GetMutator(), "Failed to fetch mutator: ");
      mutator->set_mutation_threadpool(scann_.parallel_query_pool());
    }
    result.push_back(scann_.n_points());
  }
  return result;
}

int ScannNumpy::Rebalance(const string& config) {
  pybind11::gil_scoped_release gil_release;
  absl::MutexLock lock(&mu_);
  return RebalanceLocked(config);
}

int ScannNumpy::RebalanceLocked(const string& config) {
  auto statusor = scann_.RetrainAndReindex(config);
  if (!statusor.ok()) {
    RuntimeErrorIfNotOk("Failed to retrain searcher: ", statusor.status());
    return -1;
  }

  return scann_.n_points();
}

size_t ScannNumpy::Size() const {
  pybind11::gil_scoped_release gil_release;
  absl::ReaderMutexLock lock(&mu_);
  return scann_.n_points();
}

void ScannNumpy::Reserve(size_t num_datapoints) {
  pybind11::gil_scoped_release gil_release;
  absl::MutexLock lock(&mu_);
  auto mutator =
      ValueOrRuntimeError(scann_.GetMutator(), "Failed to fetch mutator: ");
  mutator->Reserve(num_datapoints);
}

void ScannNumpy::SetNumThreads(int num_threads) {
  pybind11::gil_scoped_release gil_release;
  absl::MutexLock lock(&mu_);
  scann_.SetNumThreads(num_threads);
}

string ScannNumpy::SuggestAutopilot(absl::string_view config_str,
                                    DatapointIndex n, DimensionIndex dim) {
  ScannConfig config;
  RuntimeErrorIfNotOk("Failed to parse config: ",
                      ParseTextProto(&config, config_str));
  auto status_or = Autopilot(config, nullptr, n, dim);
  RuntimeErrorIfNotOk("Failed to suggest autopilot config: ",
                      status_or.status());
  std::string result;
  google::protobuf::TextFormat::PrintToString(status_or.value(), &result);
  return result;
}

string ScannNumpy::Config() {
  pybind11::gil_scoped_release gil_release;
  // Exclusive: ScannInterface::config() refreshes a cached copy.
  absl::MutexLock lock(&mu_);
  std::string config_str;
  google::protobuf::TextFormat::PrintToString(*scann_.config(), &config_str);
  return config_str;
}

std::pair<pybind11::array_t<DatapointIndex>, pybind11::array_t<float>>
ScannNumpy::Search(const np_row_major_arr<float>& query, int final_nn,
                   int pre_reorder_nn, int leaves) {
  if (query.ndim() != 1)
    throw std::invalid_argument("Query must be one-dimensional");

  DatapointPtr<float> ptr(nullptr, query.data(), query.size(), query.size());
  // scann-core: the results go straight into the returned arrays (upstream
  // copied them into two vectors, which pybind11 copied again).
  NNResultsVector res;
  float multiplier;
  {
    pybind11::gil_scoped_release gil_release;
    absl::ReaderMutexLock lock(&mu_);
    auto status = scann_.Search(ptr, &res, final_nn, pre_reorder_nn, leaves);
    RuntimeErrorIfNotOk("Error during search: ", status);
    multiplier = scann_.result_multiplier();
  }
  pybind11::array_t<DatapointIndex> idx(res.size());
  pybind11::array_t<float> dis(res.size());
  DatapointIndex* idx_out = idx.mutable_data();
  float* dis_out = dis.mutable_data();
  for (const auto& [i, d] : res) {
    *idx_out++ = i;
    *dis_out++ = multiplier * d;
  }
  return {std::move(idx), std::move(dis)};
}

std::pair<pybind11::array_t<DatapointIndex>, pybind11::array_t<float>>
ScannNumpy::SearchBatched(const np_row_major_arr<float>& queries, int final_nn,
                          int pre_reorder_nn, int leaves, bool parallel,
                          int batch_size) {
  if (queries.ndim() != 2)
    throw std::invalid_argument("Queries must be in two-dimensional array");

  // scann-core: upstream turned zero queries into a dataset of
  // dimensionality 0 and failed with a misleading dimensionality error (or a
  // bare RET_CHECK failure from the parallel path). Return empty results
  // shaped like a normal call's, (0, k), after the same argument checks.
  if (queries.shape()[0] == 0) {
    if (final_nn == 0)
      throw std::invalid_argument("final_num_neighbors must be > 0");
    int k;
    {
      pybind11::gil_scoped_release gil_release;
      absl::ReaderMutexLock lock(&mu_);
      if (static_cast<size_t>(queries.shape()[1]) != scann_.dimensionality())
        throw std::invalid_argument(absl::StrCat(
            "Queries have dimensionality ", queries.shape()[1],
            ", but the dataset has ", scann_.dimensionality()));
      k = final_nn > 0 ? final_nn : scann_.default_num_neighbors();
    }
    std::vector<long> shape = {0, static_cast<long>(k)};
    return {pybind11::array_t<DatapointIndex>(shape),
            pybind11::array_t<float>(shape)};
  }

  // scann-core: the queries are searched in place, with the GIL released
  // (upstream copied them first, with the GIL held, and every parallel
  // chunk copied its share again), and each chunk writes its results
  // straight into the output arrays, allocated up front (upstream reshaped
  // them serially into vectors that pybind11 then copied, with the GIL).
  const size_t n = queries.shape()[0];
  ConstSpan<float> rows(queries.data(), queries.size());
  // The arrays' width is final_nn, or with final_nn = -1 the widest result,
  // which is at most the index's default (fewer only for an index with
  // fewer points): searched into arrays that wide, and copied into narrower
  // ones in the rare case that every result is shorter.
  size_t width = 0;
  if (final_nn > 0) {
    width = final_nn;
  } else if (final_nn < 0) {
    pybind11::gil_scoped_release gil_release;
    absl::ReaderMutexLock lock(&mu_);
    width = std::max(scann_.default_num_neighbors(), 0);
  }
  std::vector<long> shape = {static_cast<long>(n), static_cast<long>(width)};
  pybind11::array_t<DatapointIndex> idx_arr(shape);
  pybind11::array_t<float> dis_arr(shape);
  DatapointIndex* idx_out = idx_arr.mutable_data();
  float* dis_out = dis_arr.mutable_data();

  std::vector<NNResultsVector> res(n);
  std::atomic<size_t> widest{0};
  std::atomic<bool> too_wide{false};
  {
    pybind11::gil_scoped_release gil_release;
    absl::ReaderMutexLock lock(&mu_);
    auto write = [&](size_t begin, ConstSpan<NNResultsVector> chunk) {
      size_t chunk_widest = 0;
      for (const auto& r : chunk) chunk_widest = std::max(chunk_widest, r.size());
      size_t prev = widest.load(std::memory_order_relaxed);
      while (prev < chunk_widest &&
             !widest.compare_exchange_weak(prev, chunk_widest)) {
      }
      if (chunk_widest > width) {
        too_wide.store(true);
        return;
      }
      scann_.ReshapeBatchedNNResult(chunk, idx_out + begin * width,
                                    dis_out + begin * width, width);
    };
    Status status =
        scann_.SearchBatchedRows(rows, queries.shape()[1],
                                 MakeMutableSpan(res), final_nn,
                                 pre_reorder_nn, leaves, parallel,
                                 parallel ? batch_size : 256, write);
    RuntimeErrorIfNotOk("Error during search: ", status);
  }
  if (!too_wide.load() && (final_nn > 0 || widest.load() == width))
    return {idx_arr, dis_arr};

  // Upstream's shape: (n, max(final_nn, widest result)).
  shape[1] = std::max<long>(final_nn, static_cast<long>(widest.load()));
  pybind11::array_t<DatapointIndex> idx2(shape);
  pybind11::array_t<float> dis2(shape);
  DatapointIndex* idx2_out = idx2.mutable_data();
  float* dis2_out = dis2.mutable_data();
  {
    pybind11::gil_scoped_release gil_release;
    absl::ReaderMutexLock lock(&mu_);
    scann_.ReshapeBatchedNNResult(MakeConstSpan(res), idx2_out, dis2_out,
                                  static_cast<int>(shape[1]));
  }
  return {idx2, dis2};
}

void ScannNumpy::Serialize(std::string path, bool relative_path,
                           std::optional<std::string> docids_pkl) {
  // scann-core: written through SerializeToDirectory, so an interrupted
  // serialize can't leave a directory that loads a mix of two indexes, and
  // the docids are committed with the index (upstream's Python wrapper
  // wrote them afterwards, and left a stale file when there were none).
  std::vector<std::pair<std::string, std::string>> extra_files;
  if (docids_pkl.has_value())
    extra_files.emplace_back("scann_docids.pkl", *std::move(docids_pkl));
  pybind11::gil_scoped_release gil_release;
  absl::MutexLock lock(&mu_);
  RuntimeErrorIfNotOk(
      "Failed to serialize searcher: ",
      scann_.SerializeToDirectory(path, relative_path, extra_files));
}

pybind11::dict ScannNumpy::GetHealthStats() const {
  StatusOr<ScannInterface::ScannHealthStats> r;
  {
    pybind11::gil_scoped_release gil_release;
    absl::MutexLock lock(&mu_);
    r = scann_.GetHealthStats();
  }
  RuntimeErrorIfNotOk("Error getting health stats: ", r.status());

  using namespace pybind11::literals;

  return pybind11::dict("avg_quantization_error"_a = r->avg_quantization_error,
                        "partition_weighted_avg_relative_imbalance"_a =
                            r->partition_weighted_avg_relative_imbalance,
                        "partition_avg_relative_positive_imbalance"_a =
                            r->partition_avg_relative_positive_imbalance,
                        "sum_partition_sizes"_a = r->sum_partition_sizes);
}

void ScannNumpy::InitializeHealthStats() {
  pybind11::gil_scoped_release gil_release;
  absl::MutexLock lock(&mu_);
  Status status = scann_.InitializeHealthStats();
  RuntimeErrorIfNotOk("Error initializing health stats: ", status);
}

}  // namespace research_scann