epzero 0.6.0__tar.gz → 1.0.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (110) hide show
  1. {epzero-0.6.0 → epzero-1.0.0}/CHANGELOG.md +46 -0
  2. epzero-1.0.0/LICENSE +21 -0
  3. epzero-1.0.0/PKG-INFO +393 -0
  4. {epzero-0.6.0 → epzero-1.0.0}/fuzz/make_seeds.cpp +6 -1
  5. {epzero-0.6.0 → epzero-1.0.0}/include/epzero/hnsw.h +16 -4
  6. {epzero-0.6.0 → epzero-1.0.0}/include/epzero/recall.h +18 -6
  7. {epzero-0.6.0 → epzero-1.0.0}/include/epzero/text.h +15 -0
  8. {epzero-0.6.0 → epzero-1.0.0}/pyproject.toml +7 -3
  9. epzero-0.6.0/PKG-INFO → epzero-1.0.0/python/README.md +118 -45
  10. epzero-1.0.0/python/epzero/collection_cli.py +158 -0
  11. epzero-1.0.0/python/epzero/collection_ids.py +50 -0
  12. {epzero-0.6.0 → epzero-1.0.0}/python/epzero/haystack.py +0 -6
  13. epzero-1.0.0/python/epzero/ingest.py +96 -0
  14. {epzero-0.6.0 → epzero-1.0.0}/python/epzero/ir.py +191 -20
  15. {epzero-0.6.0 → epzero-1.0.0}/python/epzero/langchain.py +43 -43
  16. {epzero-0.6.0 → epzero-1.0.0}/python/epzero/llamaindex.py +17 -17
  17. epzero-1.0.0/python/epzero/snapshots.py +137 -0
  18. {epzero-0.6.0 → epzero-1.0.0}/python/epzero_py.cpp +181 -79
  19. epzero-1.0.0/python/tests/data/collection-metadata/empty-exhausted-v2.json +1 -0
  20. epzero-1.0.0/python/tests/data/collection-metadata/valid-v1.json +1 -0
  21. epzero-1.0.0/python/tests/data/collection-metadata/valid-v2.json +1 -0
  22. epzero-1.0.0/python/tests/data/collection-released-0.6.0/legacy/ids.json +1 -0
  23. epzero-1.0.0/python/tests/data/collection-released-0.6.0/legacy/text.epzero +0 -0
  24. epzero-1.0.0/python/tests/data/collection-released-0.6.0/legacy/vectors.epzero +0 -0
  25. epzero-1.0.0/python/tests/data/collection-released-0.6.0/provenance.json +21 -0
  26. epzero-1.0.0/python/tests/data/collection-released-0.6.0/v1/collection.json +1 -0
  27. epzero-1.0.0/python/tests/data/collection-released-0.6.0/v1/generation-0123456789abcdef0123456789abcdef/ids.json +1 -0
  28. epzero-1.0.0/python/tests/data/collection-released-0.6.0/v1/generation-0123456789abcdef0123456789abcdef/text.epzero +0 -0
  29. epzero-1.0.0/python/tests/data/collection-released-0.6.0/v1/generation-0123456789abcdef0123456789abcdef/vectors.epzero +0 -0
  30. epzero-1.0.0/python/tests/test_collection_cli.py +107 -0
  31. epzero-1.0.0/python/tests/test_collection_compact.py +63 -0
  32. epzero-1.0.0/python/tests/test_collection_ids.py +194 -0
  33. {epzero-0.6.0 → epzero-1.0.0}/python/tests/test_epzero.py +29 -11
  34. epzero-1.0.0/python/tests/test_ingest.py +60 -0
  35. epzero-1.0.0/python/tests/test_ir.py +375 -0
  36. {epzero-0.6.0 → epzero-1.0.0}/python/tests/test_langchain.py +4 -0
  37. {epzero-0.6.0 → epzero-1.0.0}/python/tests/test_llamaindex.py +2 -0
  38. epzero-1.0.0/python/tests/test_snapshots.py +186 -0
  39. epzero-1.0.0/python/tests/test_storage_reclamation.py +99 -0
  40. {epzero-0.6.0 → epzero-1.0.0}/server/node_main.cpp +33 -12
  41. {epzero-0.6.0 → epzero-1.0.0}/src/auto.cpp +6 -2
  42. {epzero-0.6.0 → epzero-1.0.0}/src/database.cpp +41 -12
  43. {epzero-0.6.0 → epzero-1.0.0}/src/distance_avx2.cpp +48 -8
  44. {epzero-0.6.0 → epzero-1.0.0}/src/distance_avx512.cpp +22 -2
  45. {epzero-0.6.0 → epzero-1.0.0}/src/distance_avx512vnni.cpp +9 -1
  46. {epzero-0.6.0 → epzero-1.0.0}/src/distance_avxvnni.cpp +23 -3
  47. {epzero-0.6.0 → epzero-1.0.0}/src/distance_f16c.cpp +22 -2
  48. {epzero-0.6.0 → epzero-1.0.0}/src/hnsw.cpp +556 -215
  49. {epzero-0.6.0 → epzero-1.0.0}/src/metadata.cpp +77 -10
  50. {epzero-0.6.0 → epzero-1.0.0}/src/pca.h +5 -2
  51. {epzero-0.6.0 → epzero-1.0.0}/src/recall.cpp +86 -25
  52. {epzero-0.6.0 → epzero-1.0.0}/src/text.cpp +90 -17
  53. {epzero-0.6.0 → epzero-1.0.0}/src/visited_pool.h +39 -19
  54. {epzero-0.6.0 → epzero-1.0.0}/tests/database_test.cpp +19 -0
  55. {epzero-0.6.0 → epzero-1.0.0}/tests/hnsw_test.cpp +116 -0
  56. {epzero-0.6.0 → epzero-1.0.0}/tests/metadata_test.cpp +18 -0
  57. {epzero-0.6.0 → epzero-1.0.0}/tests/text_test.cpp +27 -0
  58. epzero-0.6.0/python/README.md +0 -225
  59. epzero-0.6.0/python/tests/test_ir.py +0 -160
  60. {epzero-0.6.0 → epzero-1.0.0}/CMakeLists.txt +0 -0
  61. {epzero-0.6.0 → epzero-1.0.0}/bench/bench_adaptive.cpp +0 -0
  62. {epzero-0.6.0 → epzero-1.0.0}/bench/bench_churn.cpp +0 -0
  63. {epzero-0.6.0 → epzero-1.0.0}/bench/bench_distance.cpp +0 -0
  64. {epzero-0.6.0 → epzero-1.0.0}/bench/bench_filter.cpp +0 -0
  65. {epzero-0.6.0 → epzero-1.0.0}/bench/bench_guard.cpp +0 -0
  66. {epzero-0.6.0 → epzero-1.0.0}/bench/bench_recall.cpp +0 -0
  67. {epzero-0.6.0 → epzero-1.0.0}/bench/regression.json +0 -0
  68. {epzero-0.6.0 → epzero-1.0.0}/fuzz/common.h +0 -0
  69. {epzero-0.6.0 → epzero-1.0.0}/fuzz/fuzz_graph.cpp +0 -0
  70. {epzero-0.6.0 → epzero-1.0.0}/fuzz/fuzz_metadata.cpp +0 -0
  71. {epzero-0.6.0 → epzero-1.0.0}/fuzz/fuzz_snapshot.cpp +0 -0
  72. {epzero-0.6.0 → epzero-1.0.0}/fuzz/fuzz_text.cpp +0 -0
  73. {epzero-0.6.0 → epzero-1.0.0}/fuzz/fuzz_wal.cpp +0 -0
  74. {epzero-0.6.0 → epzero-1.0.0}/fuzz/regressions/graph-empty-with-entry-point +0 -0
  75. {epzero-0.6.0 → epzero-1.0.0}/fuzz/regressions/graph-entry-level-overflow +0 -0
  76. {epzero-0.6.0 → epzero-1.0.0}/fuzz/regressions/graph-upper-link-to-base-node +0 -0
  77. {epzero-0.6.0 → epzero-1.0.0}/fuzz/regressions/snapshot-empty-with-entry-point +0 -0
  78. {epzero-0.6.0 → epzero-1.0.0}/fuzz/regressions/snapshot-huge-capacity +0 -0
  79. {epzero-0.6.0 → epzero-1.0.0}/include/epzero/auto.h +0 -0
  80. {epzero-0.6.0 → epzero-1.0.0}/include/epzero/brute_force.h +0 -0
  81. {epzero-0.6.0 → epzero-1.0.0}/include/epzero/database.h +0 -0
  82. {epzero-0.6.0 → epzero-1.0.0}/include/epzero/dataset.h +0 -0
  83. {epzero-0.6.0 → epzero-1.0.0}/include/epzero/distance.h +0 -0
  84. {epzero-0.6.0 → epzero-1.0.0}/include/epzero/metadata.h +0 -0
  85. {epzero-0.6.0 → epzero-1.0.0}/include/epzero/parallel.h +0 -0
  86. {epzero-0.6.0 → epzero-1.0.0}/python/epzero/__init__.py +0 -0
  87. {epzero-0.6.0 → epzero-1.0.0}/python/epzero/auto.py +0 -0
  88. {epzero-0.6.0 → epzero-1.0.0}/python/tests/test_auto.py +0 -0
  89. {epzero-0.6.0 → epzero-1.0.0}/python/tests/test_haystack.py +0 -0
  90. {epzero-0.6.0 → epzero-1.0.0}/python/tests/test_metadata.py +0 -0
  91. {epzero-0.6.0 → epzero-1.0.0}/src/brute_force.cpp +0 -0
  92. {epzero-0.6.0 → epzero-1.0.0}/src/dataset.cpp +0 -0
  93. {epzero-0.6.0 → epzero-1.0.0}/src/distance.cpp +0 -0
  94. {epzero-0.6.0 → epzero-1.0.0}/src/distance_neon.cpp +0 -0
  95. {epzero-0.6.0 → epzero-1.0.0}/src/distance_scalar.cpp +0 -0
  96. {epzero-0.6.0 → epzero-1.0.0}/src/distance_wasm.cpp +0 -0
  97. {epzero-0.6.0 → epzero-1.0.0}/src/half.h +0 -0
  98. {epzero-0.6.0 → epzero-1.0.0}/src/kernels.h +0 -0
  99. {epzero-0.6.0 → epzero-1.0.0}/src/platform.h +0 -0
  100. {epzero-0.6.0 → epzero-1.0.0}/src/porter.h +0 -0
  101. {epzero-0.6.0 → epzero-1.0.0}/src/rabitq.h +0 -0
  102. {epzero-0.6.0 → epzero-1.0.0}/src/sq4.h +0 -0
  103. {epzero-0.6.0 → epzero-1.0.0}/tests/auto_test.cpp +0 -0
  104. {epzero-0.6.0 → epzero-1.0.0}/tests/data/v4-from-0.4.0.epzero +0 -0
  105. {epzero-0.6.0 → epzero-1.0.0}/tests/dataset_test.cpp +0 -0
  106. {epzero-0.6.0 → epzero-1.0.0}/tests/distance_test.cpp +0 -0
  107. {epzero-0.6.0 → epzero-1.0.0}/tests/half_test.cpp +0 -0
  108. {epzero-0.6.0 → epzero-1.0.0}/tests/recall_test.cpp +0 -0
  109. {epzero-0.6.0 → epzero-1.0.0}/tools/export_graph.cpp +0 -0
  110. {epzero-0.6.0 → epzero-1.0.0}/wasm/epzero_wasm.cpp +0 -0
@@ -1,5 +1,51 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.0.0 (unreleased)
4
+
5
+ This release establishes the supported embedded Python library and local collection CLI.
6
+ See the Python 1.0 compatibility contract for API stability, persistence and operational limits.
7
+ The distributed cluster and browser demonstration remain experimental.
8
+
9
+ Collection persistence and local document workflows are the focus of this release candidate.
10
+ The native vector/text file formats remain compatible with 0.6.0; newly saved Collection metadata
11
+ uses version 2 and requires upgraded readers.
12
+
13
+ - Collection replacements stage new labels before retiring old documents. Live document metadata
14
+ no longer allocates an entry for every historical label; retired labels are never reused.
15
+ - Collection saves publish complete vector/text/ID generations through an atomic manifest.
16
+ Cooperating CLI writers coordinate the entire load/update/save operation with a folder lock.
17
+ Explicit snapshot inventory and preview-first pruning control retained disk space.
18
+ - Collection compaction rebuilds live graph and keyword structures. `shrink_capacity=True` (CLI
19
+ `--shrink-capacity`) also releases historical graph capacity; default compaction retains it.
20
+ Text rebuilding discards obsolete vocabulary and postings while preserving keyword scores.
21
+ - `epzero-collection` provides build, upsert, remove, query, inspect, compact and prune commands.
22
+ Optional local-model `embed` and `encode-query` commands prepare text vectors in batches.
23
+ Embedding output refuses overwrite and is published only after complete input succeeds.
24
+ - Source and wheel distributions include the repository's MIT license text. Release CI verifies
25
+ source-archive completeness and rebuilds/tests the archive with the optional adapter suites.
26
+ - Engine search and SIMD optimizations (+7–19% QPS on interleaved A/B benchmarks with identical
27
+ results): 4-way unrolled AVX2/AVX-VNNI/AVX-512/F16C accumulators, zero-branch specialized
28
+ `search_layer` dispatch, 8-byte inline stack `Beam` with branchless binary search, transposed
29
+ PCA outlier projection (`nav_basis_t_`), sliding-window multi-line rerank prefetch with max-heap
30
+ early stopping and `partial_sort`, and sharded word-tracked `VisitedPool`.
31
+ - Engine correctness, concurrency and memory fixes: release/acquire node publication (`ready_`)
32
+ preventing concurrent `add()`/`exact_search()`/`get_vector()` races; 8,192 cache-line-padded lock
33
+ stripes replacing per-node mutex arrays; contiguous `TombstoneBeam` eliminating the 1-tombstone
34
+ cliff; exact full-vector scanning for `FilterStrategy::Exact` on quantized/`nav_dim` indexes;
35
+ outlier splitting in `project_query()`; native C++ filtered BM25 (`TextIndex.search(filter=...)`
36
+ and `epzero.hybrid_search(filter=...)`); safe live `Index.add()`/`reserve()` growth with
37
+ `RecallGuard` attached; `SyncMode::Batch` and replica WAL pre-validation fixes; Windows-safe
38
+ atomic publication in `epzero-collection embed`; and removal of duplicate vector buffers and
39
+ load-time rebuilds across the LangChain, LlamaIndex and Haystack adapters.
40
+ - Experimental cluster fixes: 256 MiB gRPC send/recv limits on peer snapshot channels and router
41
+ dials, thread-safe shard assignment status, context-aware write retries and graceful shutdown.
42
+
43
+ Legacy and version-1 Collection snapshots remain readable. Upgrading their saved metadata is
44
+ one-way for older clients: retain a coordinated backup before saving with this candidate.
45
+ These guarantees concern cooperating processes and local filesystem snapshots, not a document
46
+ WAL, shared multi-writer service, power-loss certification or network-filesystem durability.
47
+ The changes do not establish a generally superior ANN repair algorithm or a service latency SLA.
48
+
3
49
  ## 0.6.0
4
50
 
5
51
  Indexes that keep growing without leaving their newest vectors behind; 4-bit codes; walks on principal
epzero-1.0.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Lajat Manekar
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
epzero-1.0.0/PKG-INFO ADDED
@@ -0,0 +1,393 @@
1
+ Metadata-Version: 2.2
2
+ Name: epzero
3
+ Version: 1.0.0
4
+ Summary: A fast HNSW vector database in C++20 that configures itself: SIMD search, filtered search, recall monitoring, crash-safe storage
5
+ Keywords: vector database,hnsw,ann,nearest neighbor,embeddings,rag,langchain
6
+ Author: Lajat
7
+ License: MIT License
8
+
9
+ Copyright (c) 2026 Lajat Manekar
10
+
11
+ Permission is hereby granted, free of charge, to any person obtaining a copy
12
+ of this software and associated documentation files (the "Software"), to deal
13
+ in the Software without restriction, including without limitation the rights
14
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
15
+ copies of the Software, and to permit persons to whom the Software is
16
+ furnished to do so, subject to the following conditions:
17
+
18
+ The above copyright notice and this permission notice shall be included in all
19
+ copies or substantial portions of the Software.
20
+
21
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
22
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
23
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
24
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
25
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
26
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
27
+ SOFTWARE.
28
+
29
+ Classifier: Development Status :: 5 - Production/Stable
30
+ Classifier: Intended Audience :: Developers
31
+ Classifier: Intended Audience :: Science/Research
32
+ Classifier: Programming Language :: C++
33
+ Classifier: Programming Language :: Python :: 3
34
+ Classifier: Operating System :: POSIX :: Linux
35
+ Classifier: Operating System :: MacOS
36
+ Classifier: Operating System :: Microsoft :: Windows
37
+ Classifier: Topic :: Database
38
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
39
+ Project-URL: Homepage, https://epzero.dev/
40
+ Project-URL: Source, https://github.com/Lazeeez/Epzero
41
+ Requires-Python: >=3.10
42
+ Requires-Dist: numpy
43
+ Provides-Extra: embeddings
44
+ Requires-Dist: sentence-transformers>=3; extra == "embeddings"
45
+ Provides-Extra: langchain
46
+ Requires-Dist: langchain-core>=0.3; extra == "langchain"
47
+ Provides-Extra: llamaindex
48
+ Requires-Dist: llama-index-core>=0.12; extra == "llamaindex"
49
+ Provides-Extra: haystack
50
+ Requires-Dist: haystack-ai>=2.10; extra == "haystack"
51
+ Provides-Extra: test
52
+ Requires-Dist: pytest; extra == "test"
53
+ Requires-Dist: pytest-asyncio; extra == "test"
54
+ Requires-Dist: langchain-core>=0.3; extra == "test"
55
+ Requires-Dist: langchain-tests>=0.3; extra == "test"
56
+ Requires-Dist: llama-index-core>=0.12; extra == "test"
57
+ Requires-Dist: haystack-ai>=2.10; extra == "test"
58
+ Description-Content-Type: text/markdown
59
+
60
+ # epzero
61
+
62
+ An HNSW vector search library written from scratch in C++20, with Python bindings.
63
+
64
+ The [Python 1.0 contract](https://github.com/Lazeeez/Epzero/blob/main/docs/python-1.0-contract.md) describes the supported APIs, tested platforms, snapshot migration and concurrency limits. The distributed cluster and browser demo are experimental.
65
+
66
+ **Performance evidence:** numerical comparisons below are maintainer-run experiments, not independent benchmark rankings. See the [reproduction guide](https://github.com/Lazeeez/Epzero/blob/main/BENCHMARKS.md) for versions, settings and limitations.
67
+
68
+ - **Configures itself:** `epzero.build(vectors)` picks compression, the graph build and the search
69
+ effort for your data and recall target, times memory prefetching on your CPU, saves the choices
70
+ inside the index and tells you why it made each one. Any setting can be overridden.
71
+ - **Fast search:** hand-written SIMD kernels (AVX2, AVX-512, VNNI, NEON) chosen at runtime, 8-bit
72
+ codes, an optional walk on principal directions, and lock-free reads. On dedicated Intel Xeon Gold
73
+ 6226 and AMD EPYC 7513 servers, one thread, at equal recall: 1.4-4.2× the queries per second of
74
+ Glass, the fastest library we compared, on GIST1M, OpenAI DBpedia and DEEP10M, and 1.0-1.3× on
75
+ GloVe-100 (with each dataset's best settings; see the project's scoreboard for every loss).
76
+ - **Filtered search that picks its own strategy:** an exact scan, a filtered graph walk, or a
77
+ two-hop walk (the idea behind ACORN), chosen per query by a cost model.
78
+ - **Recall you can see:** `RecallGuard` measures recall on a sample of live queries with a
79
+ confidence interval and moves the search effort to hold a target; `explain()` says why any given
80
+ item was not returned. With `per_query=True` each query also stops as soon as its answer settles,
81
+ so easy queries cost less and hard ones search further.
82
+ - **Hybrid search:** `TextIndex` (BM25 keyword search, with English stemming and native `filter=`
83
+ support) and `hybrid_search(..., filter=...)`, which merges it with vector search by reciprocal
84
+ rank fusion.
85
+ - **Retrieval evaluation:** `epzero.ir` keeps documents under string ids, runs dense, keyword and
86
+ hybrid retrieval, writes TREC run files and scores them against relevance judgements exactly as
87
+ trec_eval does. On BEIR with all-MiniLM-L6-v2, hybrid reaches nDCG@10 0.713 on SciFact and 0.354 on
88
+ NFCorpus, above either half alone.
89
+ - **Durable:** `Database` adds a write-ahead log with crash recovery and checkpoints.
90
+ - **8-bit quantization** with exact re-ranking, stopped early per query once the rest can't reach
91
+ the top k.
92
+ - **Stays accurate as data changes:** `health()` says when an index needs recalibrating,
93
+ requantizing, compacting or rebuilding, and each fix runs in place.
94
+ - **LangChain, LlamaIndex and Haystack** stores, each passing its framework's own test suite,
95
+ reading vectors directly from the engine and persisting native index files directly.
96
+
97
+ ```bash
98
+ pip install epzero # the engine
99
+ pip install "epzero[langchain]" # plus the LangChain vector store
100
+ pip install "epzero[llamaindex]" # plus the LlamaIndex vector store
101
+ pip install "epzero[haystack]" # plus the Haystack document store and retriever
102
+ ```
103
+
104
+ ## Quick start: let it configure itself
105
+
106
+ ```python
107
+ import numpy as np
108
+ import epzero
109
+
110
+ vectors = np.random.rand(100_000, 768).astype(np.float32)
111
+ index = epzero.build(vectors, metric="cosine") # chooses every setting (below)
112
+ labels, distances = index.search(vectors[:5], k=10) # at the effort calibrated for recall 0.95
113
+ print(index.plan) # what it chose, and why
114
+ ```
115
+
116
+ `build` decides from the data: 8-bit compression, whether to walk on principal directions (high
117
+ dimensions with a concentrated spectrum), the build passes, the re-rank, and the beam width that
118
+ reaches your recall target, measured on rows held out of the graph. From the machine: the SIMD
119
+ kernel, the prefetch setting (timed on this CPU) and every core. Change anything:
120
+
121
+ ```python
122
+ index = epzero.build(vectors, metric="cosine", recall=0.99) # a different target
123
+ index = epzero.build(vectors, metric="cosine", queries=my_queries) # calibrate on real queries
124
+ index = epzero.build(vectors, metric="cosine", nav_dim=0, refine=False, M=32) # override choices
125
+ plan = epzero.plan(vectors, metric="cosine") # look before building, edit, then pass it in
126
+ index = epzero.build(vectors, plan=plan.replace(ef_construction=400))
127
+ labels, distances = index.search(queries, k=50, ef=200) # per-call overrides
128
+ index.save("my.epz") # the settings and reasons are saved inside it
129
+ index = epzero.Index.load("my.epz") # search() uses them again
130
+ ```
131
+
132
+ `build` returns an ordinary `epzero.Index`: filters, deletes, `explain()` and `RecallGuard` all use
133
+ its settings. A saved index re-applies its prefetch setting only on the same kind of CPU (call
134
+ `tune_prefetch()` on another). The decisions are made in the C++ engine (`epzero/auto.h`), so C++
135
+ users get the same `build_auto()`.
136
+
137
+ If your queries differ from your data (text queries against image vectors, say), pass a few
138
+ hundred of them as `queries=`: recall calibrated on data rows is optimistic for those.
139
+
140
+ **Metadata.** Fields per label, filtered in the engine:
141
+
142
+ ```python
143
+ meta = epzero.Metadata()
144
+ meta.set_many(labels, [{"source": "faq", "year": 2024}, ...])
145
+ allowed = meta.select({"source": ["faq", "docs"], "year": {"$gte": 2022}})
146
+ labels, distances = index.search(queries, k=10, filter=index.filter(allowed))
147
+ ```
148
+
149
+ **After the build.** An index keeps changing; its calibration doesn't, by itself:
150
+
151
+ ```python
152
+ print(index.health()) # growth since calibration, deleted share, code error, fit of the directions, advice
153
+ print(index.check_queries(queries)) # do these queries look like the data? (text vs images: no)
154
+ index.recalibrate(queries) # re-measure the beam width on real queries; saved in the profile
155
+ index.requantize() # vectors drifted outside the 8-bit codes' ranges: refit and reconnect
156
+ guard = epzero.RecallGuard(index, sample_rate=0.01) # or measure live recall and adjust as you go
157
+ ```
158
+
159
+ When later vectors drift outside the ranges the 8-bit codes were fitted on, they are clipped and
160
+ the graph links chosen for them suffer: in a synthetic test with a 4 sd drift, the beam width needed
161
+ for recall 0.95 went from 12 to 200. `requantize()` refits the codes and reconnects the graph in about half a rebuild's
162
+ time, back to 12.
163
+
164
+ **An index that keeps growing.** In a graph index, a vector inserted early keeps gaining incoming links
165
+ from everything added near it later, and one inserted late has had no time to. So the newest vectors are
166
+ found less often than in a fresh build of the same data. Two options make an index grown in batches
167
+ behave like a rebuild:
168
+
169
+ ```python
170
+ index = epzero.build(vectors, extra_backlinks=8) # each insertion is also linked from 8 nearby nodes
171
+ ...
172
+ first = len(index) # before a batch (nothing removed since)
173
+ index.add(batch, labels=batch_labels)
174
+ index.refine_links(ef=100, first=first) # at a checkpoint: reconnect the batch, all cores
175
+
176
+ index = epzero.Index.load(path)
177
+ index.set_extra_backlinks(8) # not saved with the index: set it again after load
178
+ ```
179
+
180
+ Both are off by default. A one-off build gains nothing from them; they are for indexes that keep
181
+ growing. The checkpoint refine visits only the vectors added since `first`, so it takes a small
182
+ fraction of a rebuild's time.
183
+
184
+ ## Configured by hand
185
+
186
+ ```python
187
+ vectors = np.random.rand(100_000, 128).astype(np.float32)
188
+ index = epzero.Index(dim=128, metric="l2", max_elements=100_000, M=16, ef_construction=200)
189
+ index.add(vectors) # labels 0..n-1 (or pass labels=); grows as needed
190
+
191
+ labels, distances = index.search(vectors[:5], k=10, ef=64)
192
+
193
+ # Filtered search: compile the allowed labels once, reuse across queries.
194
+ allowed = index.filter(np.arange(0, 100_000, 50))
195
+ labels, distances = index.search(vectors[:5], k=10, filter=allowed)
196
+
197
+ # Hold recall at 0.95 as the workload drifts, checking 1% of queries; per_query=True lets each
198
+ # query stop once its answer settles (cheaper for the same recall).
199
+ guard = epzero.RecallGuard(index, target=0.95, sample_rate=0.01, reference_ef=1024, per_query=True)
200
+ labels, distances = guard.search(vectors[:5], k=10)
201
+ print(guard.report())
202
+
203
+ # Optional: measure the best memory-prefetch setting for this machine and data (not saved).
204
+ index.tune_prefetch(vectors[:500])
205
+
206
+ index.save("vectors.epzero")
207
+ index = epzero.Index.load("vectors.epzero")
208
+
209
+ # Hybrid: keyword search on the same labels, merged with the vector search (optional native filter).
210
+ text = epzero.TextIndex()
211
+ text.add(None, documents) # labels 0..n-1, matching the index
212
+ labels, scores = epzero.hybrid_search(index, text, query_vector, "error E-1042 at checkout", k=10)
213
+ labels, scores = epzero.hybrid_search(index, text, query_vector, "error E-1042", k=10, filter=allowed_labels)
214
+ ```
215
+
216
+ ## LangChain
217
+
218
+ ```python
219
+ from langchain_openai import OpenAIEmbeddings
220
+ from epzero.langchain import EpzeroVectorStore
221
+
222
+ store = EpzeroVectorStore.from_texts(texts, OpenAIEmbeddings(), metadatas=metadatas)
223
+ store.similarity_search("how do I reset my password?", k=4, filter={"source": "faq"})
224
+ store.max_marginal_relevance_search("pricing", k=4, fetch_k=20)
225
+ store.hybrid_search("error E-1042 at checkout", k=4) # keywords + vectors
226
+ retriever = store.as_retriever(search_kwargs={"k": 8})
227
+
228
+ store.save_local("./store")
229
+ store = EpzeroVectorStore.load_local("./store", OpenAIEmbeddings())
230
+ ```
231
+
232
+ Metadata filters are a dict of required values (a list means "any of"), or a callable on the
233
+ metadata. They are compiled into an Epzero filter, so both similarity search and `hybrid_search()`
234
+ filter natively in C++ instead of over-fetching and discarding. Vectors stay in the engine (no
235
+ duplicate Python vector array), and `save_local()`/`load_local()` persist native `index.epzero`,
236
+ `keywords.epzero` and `metadata.epzero` directly. The store passes LangChain's standard
237
+ vector-store test suite.
238
+
239
+ ## LlamaIndex
240
+
241
+ ```python
242
+ from llama_index.core import StorageContext, VectorStoreIndex
243
+ from epzero.llamaindex import EpzeroVectorStore
244
+
245
+ store = EpzeroVectorStore(metric="cosine")
246
+ index = VectorStoreIndex.from_documents(documents, storage_context=StorageContext.from_defaults(vector_store=store))
247
+ index.as_query_engine().query("How do I reset my password?")
248
+ store.persist("./epzero-store") # EpzeroVectorStore.from_persist_path("./epzero-store")
249
+ ```
250
+
251
+ Metadata filters (`==`, `!=`, `>`, `>=`, `<`, `<=`, `in`, `nin`, combined with AND or OR) run in the
252
+ engine, as do `doc_ids` and `node_ids`; `delete_ref_doc` removes a document's nodes. Vectors stay
253
+ in the engine and `persist()`/`from_persist_path()` save and load `index.epzero` directly without
254
+ rebuilding HNSW on load.
255
+
256
+ ## Haystack
257
+
258
+ ```python
259
+ from haystack import Pipeline
260
+ from epzero.haystack import EpzeroDocumentStore, EpzeroEmbeddingRetriever
261
+
262
+ store = EpzeroDocumentStore(metric="cosine")
263
+ store.write_documents(documents) # Documents with embeddings
264
+ pipeline = Pipeline()
265
+ pipeline.add_component("retriever", EpzeroEmbeddingRetriever(document_store=store, top_k=5))
266
+ pipeline.run({"retriever": {"query_embedding": embedding,
267
+ "filters": {"field": "meta.lang", "operator": "==", "value": "en"}}})
268
+ ```
269
+
270
+ Filters use Haystack's syntax and run in the engine wherever that gives exactly Haystack's answer;
271
+ the rest (ranges on dates, `None`) go to Haystack's reference implementation. The store passes
272
+ Haystack's document-store test suite.
273
+
274
+ ## Retrieval evaluation
275
+
276
+ ```python
277
+ from epzero import ir
278
+
279
+ corpus, queries, qrels = ir.load_beir("scifact") # a BEIR dataset folder
280
+ collection = ir.Collection.build(list(corpus), doc_vectors, texts=list(corpus.values()), metric="cosine")
281
+ run = collection.retrieve(list(queries), vectors=query_vectors, texts=list(queries.values()),
282
+ k=100, mode="hybrid") # or "dense", "keyword"
283
+ ir.write_run(run, "run.txt", tag="my-system") # TREC format, for CLEF or TREC
284
+ print(ir.evaluate(run, qrels)) # nDCG@10, R@100, MAP, MRR@10
285
+ ```
286
+
287
+ `evaluate` matches trec_eval (tested against it, ties included) and also takes `per_query=True` and
288
+ measures like `P@5` or `nDCG@20`. Documents can be added, replaced and removed by id, and a collection
289
+ saves to a folder. `Collection.add` validates vectors and text before changing existing documents,
290
+ and stages replacements before removing their old records. A failed native insertion is cleaned up
291
+ but can leave graph tombstones; this is not a durable document transaction.
292
+
293
+ `collection.save(folder)` publishes vectors, text and document IDs as one generation through an
294
+ atomic manifest replacement. A failed save before publication leaves the previous snapshot readable.
295
+ `ir.Collection.load(folder)` also reads legacy folders. Saves retain old and unfinished generations,
296
+ so budget disk space for full snapshots. Wrapper operations on one Collection object are serialized.
297
+ Loads, saves and cleanup coordinate through a folder lock; direct native index access still needs
298
+ caller coordination. Separate loaded objects remain last-writer-wins when saved.
299
+ Windows folder locks also serialize readers and can time out under contention.
300
+ See [collection snapshot semantics](../../docs/file-format.md#collection-snapshots) for recovery,
301
+ compatibility and platform limits.
302
+
303
+ ## Local collection command
304
+
305
+ The source package installs `epzero-collection` (also available as `python -m epzero.collection_cli`).
306
+ Provide one JSON object per line in `documents.jsonl`, using embeddings from your chosen model:
307
+
308
+ ```json
309
+ {"id":"guide","vector":[1,0],"text":"Getting started with local search"}
310
+ {"id":"backup","vector":[0,1],"text":"Saving and restoring your documents"}
311
+ ```
312
+
313
+ ```bash
314
+ epzero-collection build ./documents documents.jsonl --metric cosine
315
+ epzero-collection query ./documents --vector '[1,0]' --k 2
316
+ epzero-collection query ./documents --mode keyword --text 'saving documents' --k 2
317
+ epzero-collection upsert ./documents updates.jsonl
318
+ epzero-collection remove ./documents guide
319
+ epzero-collection inspect ./documents
320
+ epzero-collection compact ./documents --threads 1 # rebuild the graph without tombstones, then save
321
+ epzero-collection prune ./documents --keep 2 # preview sizes and generation names
322
+ epzero-collection prune ./documents --keep 2 --apply # explicit cleanup
323
+ ```
324
+
325
+ `build` requires a new folder; `upsert` replaces matching IDs. Updates and removals hold a folder
326
+ lock across loading, mutation and saving, so cooperating CLI writers cannot overwrite each other's
327
+ updates. Inputs must have unique IDs, finite vectors of equal dimension, and text for every row or
328
+ none. Use the same embedding model and dimensions for documents and queries. Inputs are loaded into
329
+ memory; this command does not generate embeddings or provide a hosted search service.
330
+
331
+ `inspect` reports live documents, historical allocation counters (`label_slots` and
332
+ `retired_label_slots`), `live_label_entries`, native tombstones, capacity, estimated native bytes and
333
+ snapshot disk bytes. Historical counters are not allocated Python slots: the live-label maps and
334
+ version-2 metadata contain only live entries. Native bytes exclude Python and process overhead.
335
+ Cleanup keeps the committed snapshot plus
336
+ the newest unreferenced generations; those extras may include interrupted saves. Do not delete the
337
+ `.collection.lock` file or run cleanup alongside older library versions that do not acquire it.
338
+
339
+ `compact` removes graph tombstones and unused keyword storage through a rebuild and publishes the result under the same folder
340
+ lock as an update. It keeps document IDs and keyword data, but can change approximate search results.
341
+ It temporarily holds both graphs and text indexes and retains the next-label counter. Native
342
+ capacity is retained by default; `compact --shrink-capacity` reserves only the live graph size
343
+ (one slot for an empty collection). Later inserts can grow it again.
344
+ It rebuilds the live-label maps to release excess Python hash-table capacity. Its JSON report
345
+ distinguishes removed tombstones, live metadata entries and estimated native memory.
346
+ Compaction and snapshot cleanup serve different purposes; old snapshots remain until explicitly pruned.
347
+ The Python equivalent is `collection.compact(threads=1)`, followed by `collection.save(folder)`.
348
+ Pass `shrink_capacity=True` to reclaim graph capacity. `inspect` includes `text_storage`: live
349
+ documents, document slots, stored/live terms and postings. These counts are not process RSS.
350
+ The text index also reclaims dead vocabulary during its existing automatic cleanup trigger.
351
+
352
+ ### From text to a searchable collection
353
+
354
+ From the repository root, install `pip install "./engine[embeddings]"` and supply an already downloaded Sentence Transformers
355
+ model directory. Input `texts.jsonl` contains one `{"id":"guide","text":"Your text"}` per line.
356
+
357
+ ```bash
358
+ epzero-collection embed texts.jsonl vectors.jsonl --model ./models/my-encoder --batch-size 32
359
+ epzero-collection build ./documents vectors.jsonl --metric cosine
360
+ epzero-collection encode-query 'How do I save my documents?' --model ./models/my-encoder
361
+ epzero-collection query ./documents --vector '[paste the vector printed above]' --k 5
362
+ epzero-collection query ./documents --mode keyword --text 'save documents' --k 5
363
+ ```
364
+
365
+ The encoder runs locally on CPU by default (`--device` selects another device). No model is
366
+ downloaded implicitly. Use the same model snapshot for documents, updates and queries; use
367
+ `--prefix` for a model's required document/query instructions. The model's default prompt is
368
+ disabled so the explicit prefix controls the input. Long texts follow the model's truncation
369
+ behavior: split them into meaningful chunks with stable IDs before ingestion. Source text is
370
+ retained for keyword indexing; query output returns IDs and scores, not stored source passages.
371
+ The collection does not persist or enforce encoder identity, so retain the model/configuration
372
+ with your application. [Sentence Transformers API](https://www.sbert.net/docs/package_reference/sentence_transformer/model.html).
373
+
374
+ `embed` batches text and vectors, retaining an ID set to reject duplicates. It refuses an
375
+ existing output file and publishes atomically only after encoding succeeds (via hard link on
376
+ POSIX and atomic no-overwrite rename on Windows). Collection `build` still loads the vector JSONL
377
+ into memory. The Python API `epzero.ingest.encode_jsonl(input, output, encode)` accepts any callable
378
+ that returns a finite, nonzero vector for each supplied text, without requiring this optional model
379
+ dependency. Embedding quality and source-document chunking remain application choices.
380
+
381
+ New saves use collection metadata version 2. Legacy folders and version-1 snapshots load without
382
+ changing native labels or keyword data; saving upgrades their metadata. Older collection readers
383
+ cannot read version 2. Migration can temporarily require memory for the old dense label array.
384
+ The fix bounds metadata entry count by live documents, not total process memory under arbitrary
385
+ updates; native capacity, text vocabulary and retained snapshots have separate storage costs.
386
+ Sparse maps have more overhead per live entry than a dense array, so the benefit is strongest after
387
+ replacement/deletion history accumulates; a newly built collection may use more metadata bytes.
388
+
389
+ ## Platforms
390
+
391
+ Wheels for Linux (x86-64 and ARM64, glibc 2.28+), macOS (Apple silicon and Intel) and Windows (x64), Python 3.10 to 3.13. Elsewhere, `pip install epzero` builds from source (CMake 3.20+, a C++20 compiler).
392
+
393
+ Live demo, benchmarks and design notes: https://epzero.dev/ · MIT license.
@@ -21,7 +21,7 @@ int main(int argc, char** argv) {
21
21
  return 2;
22
22
  }
23
23
  const fs::path out = argv[1];
24
- for (const char* name : {"snapshot", "graph", "wal", "text", "metadata"}) fs::create_directories(out / name);
24
+ for (const char* name : {"snapshot", "graph", "wal", "text", "metadata", "collection"}) fs::create_directories(out / name);
25
25
 
26
26
  std::vector<float> vectors(40 * kDim);
27
27
  for (std::size_t i = 0; i < vectors.size(); ++i) vectors[i] = static_cast<float>((i * 7919) % 101) / 101.0f;
@@ -79,6 +79,11 @@ int main(int argc, char** argv) {
79
79
  meta.set(1, {{"source", std::string("faq")}, {"year", std::int64_t{2021}}, {"public", true}});
80
80
  meta.set(2, {{"source", std::string("blog")}, {"score", 0.5}});
81
81
  meta.save((out / "metadata" / "valid").string());
82
+ // Collection IDs are a Python-level format. These seeds also feed its mutation/property tests;
83
+ // they are not native index snapshots and must not be passed to the snapshot fuzz target.
84
+ std::ofstream(out / "collection" / "valid-v1.json") << R"(["first",null,"third"])";
85
+ std::ofstream(out / "collection" / "valid-v2.json") << R"({"next_label":11,"documents":[[0,"first"],[9,"tenth"]]})";
86
+ std::ofstream(out / "collection" / "empty-exhausted-v2.json") << R"({"next_label":9223372036854775808,"documents":[]})";
82
87
  std::printf("seeds written to %s\n", out.string().c_str());
83
88
  return 0;
84
89
  }
@@ -258,7 +258,8 @@ class HnswIndex {
258
258
  // A fresh index holding only the live vectors (same parameters), for reclaiming the space of
259
259
  // deleted nodes. Requires full-precision vectors (always true unless SQ8 without keep_vectors,
260
260
  // where the decoded approximations are used instead).
261
- std::unique_ptr<HnswIndex> compacted(std::size_t threads = 0) const;
261
+ // shrink_capacity reserves only max(1, live_count()) slots in the replacement.
262
+ std::unique_ptr<HnswIndex> compacted(std::size_t threads = 0, bool shrink_capacity = false) const;
262
263
 
263
264
  // Once the index is built: gives each node's free layer-0 link slots to its closest two-hop
264
265
  // neighbours. A cheaper way than fill_links to the same end, as links added here are never pruned
@@ -334,7 +335,7 @@ class HnswIndex {
334
335
  // differences are noise). Machine-specific, so not saved with the index: tune after loading.
335
336
  // Measured: +17% on GloVe-100 at full precision, nothing on GIST1M with SQ8. Returns the setting.
336
337
  std::pair<std::size_t, std::size_t> tune_prefetch(const float* queries, std::size_t n, std::size_t k = 10,
337
- std::size_t ef = 64);
338
+ std::size_t ef = 64, std::size_t rerank = 0, float rerank_z = 0.0f);
338
339
 
339
340
  // The stored vector of `label` (dim floats, normalized for cosine; decoded from the codes if the full
340
341
  // vectors aren't kept). Returns false if the label isn't live.
@@ -407,6 +408,8 @@ class HnswIndex {
407
408
  void fit_code_ranges(std::size_t n, const std::function<bool(std::size_t, float*)>& row, std::size_t threads);
408
409
  void decode(id_t id, float* out) const noexcept;
409
410
  bool is_deleted(id_t id) const noexcept;
411
+ bool is_ready(id_t id) const noexcept;
412
+ std::mutex& node_lock(id_t id) const noexcept { return node_locks_[id & (kLockStripes - 1)].mu; }
410
413
 
411
414
  // Layout of a neighbor list: [count, id_0, id_1, ..., id_{capacity-1}].
412
415
  id_t* links_of(id_t id, int layer) noexcept;
@@ -480,10 +483,12 @@ class HnswIndex {
480
483
  std::vector<float> nav_basis_; // nav_dim: the directions, nav_dim rows of dim floats
481
484
  DistanceFn dot_ = nullptr; // nav_dim: 1 - dot, to project a vector
482
485
  // nav_dim, for queries: nav_basis_ rounded to int8, one row at a time, with each row's scale and
483
- // sum. Not saved: rebuilt from nav_basis_.
486
+ // sum, plus a transposed float copy (dim x nav_dim) so outlier coordinates accumulate contiguously.
487
+ // Not saved: rebuilt from nav_basis_.
484
488
  std::vector<std::int8_t> nav_ibasis_;
485
489
  std::vector<float> nav_iscale_;
486
490
  std::vector<std::int64_t> nav_isum_;
491
+ std::vector<float> nav_basis_t_;
487
492
  std::unique_ptr<float[], AlignedFree> full_;
488
493
  std::unique_ptr<std::uint16_t[], AlignedFree> half_; // instead of full_, with half_vectors
489
494
  HalfDistanceFn dist_half_ = nullptr;
@@ -499,9 +504,16 @@ class HnswIndex {
499
504
  std::vector<std::int8_t> levels_;
500
505
  std::vector<std::uint64_t> labels_;
501
506
  std::unique_ptr<std::uint8_t[]> deleted_; // tombstones, accessed atomically
507
+ std::unique_ptr<std::uint8_t[]> ready_; // set after vector/codes/label are written, accessed atomically
502
508
  std::atomic<std::size_t> deleted_count_{0};
503
509
 
504
- std::unique_ptr<std::mutex[]> node_locks_;
510
+ // Striped per-node writer locks (cache-line padded to avoid false sharing): a thread never holds
511
+ // two node locks at once, so striping cannot deadlock and saves 40-80 bytes per capacity slot.
512
+ static constexpr std::size_t kLockStripes = 8192;
513
+ struct alignas(64) PaddedMutex {
514
+ std::mutex mu;
515
+ };
516
+ mutable std::unique_ptr<PaddedMutex[]> node_locks_;
505
517
  std::mutex entry_lock_;
506
518
  std::atomic<std::uint64_t> entry_{kEmpty};
507
519
  std::atomic<std::size_t> count_{0};
@@ -9,6 +9,7 @@
9
9
  // interval per traffic segment. RecallGuard closes the loop: it searches each segment at the
10
10
  // smallest beam width whose measured recall stays above a target.
11
11
 
12
+ #include <array>
12
13
  #include <atomic>
13
14
  #include <condition_variable>
14
15
  #include <cstddef>
@@ -19,6 +20,7 @@
19
20
  #include <memory>
20
21
  #include <mutex>
21
22
  #include <optional>
23
+ #include <shared_mutex>
22
24
  #include <string>
23
25
  #include <thread>
24
26
  #include <vector>
@@ -46,6 +48,9 @@ class RecallMonitor {
46
48
  // ef 1024 is 31x cheaper than a scan with recall 0.9995: the estimate is off by at most the
47
49
  // reference's own misses, in either direction.
48
50
  std::size_t reference_ef = 0;
51
+ // Optional shared_mutex held (shared) by the background worker during exact checks, allowing
52
+ // callers to grow/reserve the index safely under an exclusive lock while a monitor is attached.
53
+ std::shared_mutex* index_lock = nullptr;
49
54
  };
50
55
 
51
56
  explicit RecallMonitor(const HnswIndex& index) : RecallMonitor(index, Options{}) {}
@@ -58,6 +63,9 @@ class RecallMonitor {
58
63
  // monitor's own thread; the caller never waits (a full queue drops the sample instead).
59
64
  void observe(const float* query, std::size_t k, const std::vector<SearchResult>& results,
60
65
  const SearchFilter* filter = nullptr, const std::string& segment = "all");
66
+ // Zero-copy filter overload: retains a shared reference instead of deep-copying SearchFilter.
67
+ void observe(const float* query, std::size_t k, const std::vector<SearchResult>& results,
68
+ std::shared_ptr<const SearchFilter> filter, const std::string& segment = "all");
61
69
 
62
70
  RecallEstimate estimate(const std::string& segment = "all") const;
63
71
  std::vector<std::pair<std::string, RecallEstimate>> segments() const;
@@ -77,7 +85,7 @@ class RecallMonitor {
77
85
  std::vector<float> query;
78
86
  std::size_t k;
79
87
  std::vector<std::uint64_t> returned;
80
- std::optional<SearchFilter> filter;
88
+ std::shared_ptr<const SearchFilter> filter;
81
89
  std::string segment;
82
90
  };
83
91
  void run();
@@ -128,6 +136,8 @@ class RecallGuard {
128
136
 
129
137
  std::vector<SearchResult> search(const float* query, std::size_t k, const SearchFilter* filter = nullptr,
130
138
  SearchStats* stats = nullptr);
139
+ std::vector<SearchResult> search(const float* query, std::size_t k, std::shared_ptr<const SearchFilter> filter,
140
+ SearchStats* stats = nullptr);
131
141
 
132
142
  struct Segment {
133
143
  std::string name;
@@ -143,18 +153,20 @@ class RecallGuard {
143
153
  static std::string segment_of(const SearchFilter* filter);
144
154
 
145
155
  private:
156
+ static constexpr std::size_t kNumSegments = 5;
157
+ static std::size_t segment_index(const SearchFilter* filter) noexcept;
158
+ static const char* segment_name(std::size_t idx) noexcept;
159
+
146
160
  struct State {
147
- std::atomic<std::size_t> ef;
161
+ std::atomic<std::size_t> ef{64};
148
162
  std::atomic<std::size_t> changes{0};
149
- explicit State(std::size_t initial) : ef(initial) {}
163
+ std::atomic<bool> active{false};
150
164
  };
151
- State& state(const std::string& segment);
152
165
  void adjust(const std::string& segment);
153
166
 
154
167
  const HnswIndex& index_;
155
168
  Options options_;
156
- mutable std::mutex states_lock_;
157
- std::map<std::string, std::unique_ptr<State>> states_;
169
+ std::array<State, kNumSegments> states_;
158
170
  // Last, so it is destroyed first: its thread calls adjust(), which uses the members above.
159
171
  RecallMonitor monitor_;
160
172
  };