codenib.index.embedding
¶
Embedding module for CodeNib. Provides vector storage and semantic search capabilities for code chunks.
Modules:
| Name | Description |
|---|---|
builders |
Reusable embedding builders for hierarchical pipelines. |
model_policy |
Embedding model defaults and remote-code trust policy. |
prompt_registry |
Per-model prompt registry for sentence-transformer embedders. |
vector_store |
Vector Store implementation using FAISS and sentence-transformers for code embeddings. |
Classes:
| Name | Description |
|---|---|
VectorStoreBuilder |
Builder class wrapping common vector store build operations. |
CodeVectorStore |
Vector store for code embeddings using FAISS and sentence-transformers. |
Functions:
| Name | Description |
|---|---|
build_hierarchical_vector_store |
Build (or load) a hierarchical vector store (L0/L2) for a repository. |
create_code_vector_store |
Factory function to create a CodeVectorStore. |
VectorStoreBuilder
¶
CodeVectorStore
¶
CodeVectorStore(
embedding_model: str = "text-embedding-ada-002",
embedding_provider: str = "openai",
dimension: int = 1536,
index_type: str = "flat",
index_metric: str = "ip",
ivf_nlist: int = 100,
ivf_nprobe: int = 8,
store_path: str | None = None,
profiler: Profiler | None = None,
embedding: Any | None = None,
**embedding_kwargs
)
Vector store for code embeddings using FAISS and sentence-transformers. Provides semantic search capabilities over code chunks.
Supports hierarchical indexing: - L0: File-level skeletons - L2: Function/method-level chunks for fine-grained retrieval (default)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
embedding_model
|
str
|
Name of the embedding model to use |
'text-embedding-ada-002'
|
embedding_provider
|
str
|
Provider for embeddings ("openai", "huggingface") |
'openai'
|
dimension
|
int
|
Dimension of the embedding vectors |
1536
|
index_type
|
str
|
FAISS index type — "flat" (exact brute force, default) or "ivf" (IVF inverted-file; approximate, faster at scale). IVF indices are trained lazily on the first batch of vectors. |
'flat'
|
index_metric
|
str
|
Distance metric ("ip" for inner product, "l2" for L2 distance) |
'ip'
|
ivf_nlist
|
int
|
IVF only — number of Voronoi cells (coarse centroids). On
small corpora it is clamped down to the training-set size, since
FAISS k-means needs at least |
100
|
ivf_nprobe
|
int
|
IVF only — cells probed per query; the recall/latency
knob. Clamped to the effective |
8
|
store_path
|
str | None
|
Path to store/load the vector store |
None
|
profiler
|
Profiler | None
|
Optional profiler instance to capture detailed timings |
None
|
embedding
|
Any | None
|
A pre-built embedding wrapper to reuse. When several stores share one model (e.g. one per repo), pass the same instance so the model is loaded onto the GPU only once. |
None
|
**embedding_kwargs
|
Additional arguments for embedding model |
{}
|
Methods:
| Name | Description |
|---|---|
reuse_query_embedding |
Reuse one query vector within a composed request, then discard it. |
clear_query_cache |
Clear the single-query embedding reused by consecutive search stages. |
swap_index |
Hot-swap the FAISS index without reloading the embedding model. |
close |
Release embeddings and FAISS resources to free memory. |
add_code_chunks |
Add code chunks to the vector store. |
add_nodes_with_content |
Add NodeInfo objects (with content) to the vector store. |
search |
Search for similar code chunks using semantic similarity. |
search_with_content |
Search and return results with content included. |
search_within_ids |
Search only within a restricted set of node IDs. |
hierarchical_search |
Note: This method is implemented by Claude and is just for future reference. |
save |
Save the vector store to disk. |
load |
Load the vector store from disk. |
get_stats |
Get statistics about the vector store. |
get_embeddings_by_content_hash |
Extract raw embedding vectors from the FAISS index, keyed by content hash. |
rebuild_from_embeddings |
Clear level and rebuild its FAISS index from pre-computed embeddings. |
delta_update |
Patch the FAISS index in place when the change set is small. |
clear |
Clear data from the vector store. |
Source code in codenib/index/embedding/vector_store.py
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 | |
reuse_query_embedding
¶
Reuse one query vector within a composed request, then discard it.
Source code in codenib/index/embedding/vector_store.py
clear_query_cache
¶
Clear the single-query embedding reused by consecutive search stages.
swap_index
¶
Hot-swap the FAISS index without reloading the embedding model.
Frees the current L0/L2 FAISS indices and documents from memory, then loads a new index from path. The embedding model is left intact so the caller can reuse the same model across many instances.
Source code in codenib/index/embedding/vector_store.py
close
¶
Release embeddings and FAISS resources to free memory.
Source code in codenib/index/embedding/vector_store.py
add_code_chunks
¶
Add code chunks to the vector store.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
code_chunks
|
list[dict[str, Any]]
|
List of code chunk dictionaries with content and metadata |
required |
level
|
Level
|
Index level to add chunks to ("l0" for file skeletons, "l2" for functions/methods) |
'l2'
|
Source code in codenib/index/embedding/vector_store.py
add_nodes_with_content
¶
add_nodes_with_content(nodes: list[NodeInfo], level: Level = 'l2') -> None
Add NodeInfo objects (with content) to the vector store.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
nodes
|
list[NodeInfo]
|
List of NodeInfo objects |
required |
level
|
Level
|
Index level to add nodes to ("l0" or "l2") |
'l2'
|
Source code in codenib/index/embedding/vector_store.py
search
¶
search(
query: str,
top_k: int = 10,
score_threshold: float | None = None,
level: Level = "l2",
mask_node_ids: set[str] | None = None,
) -> list[NodeInfo]
Search for similar code chunks using semantic similarity.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
query
|
str
|
Search query text |
required |
top_k
|
int
|
Number of top results to return |
10
|
score_threshold
|
float | None
|
Minimum similarity score threshold |
None
|
level
|
Level
|
Index level to search ("l0" for file skeletons, "l2" for functions/methods) |
'l2'
|
mask_node_ids
|
set[str] | None
|
Optional set of CodeChunk.node_id values to filter results. |
None
|
Returns:
| Type | Description |
|---|---|
list[NodeInfo]
|
List of NodeInfo objects with scores populated |
Source code in codenib/index/embedding/vector_store.py
search_with_content
¶
search_with_content(
query: str,
top_k: int = 10,
score_threshold: float | None = None,
level: Level = "l2",
mask_node_ids: set[str] | None = None,
) -> list[NodeInfo]
Search and return results with content included.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
query
|
str
|
Search query text |
required |
top_k
|
int
|
Number of top results to return |
10
|
score_threshold
|
float | None
|
Minimum similarity score threshold |
None
|
level
|
Level
|
Index level to search ("l0" for file skeletons, "l2" for functions/methods) |
'l2'
|
mask_node_ids
|
set[str] | None
|
Optional set of CodeChunk.node_id values to filter results. |
None
|
Returns:
| Type | Description |
|---|---|
list[NodeInfo]
|
List of NodeInfo objects with content populated |
Source code in codenib/index/embedding/vector_store.py
search_within_ids
¶
search_within_ids(
query: str, mask_node_ids: set[str], top_k: int = 10, level: Level = "l2"
) -> list[NodeInfo]
Search only within a restricted set of node IDs.
Instead of searching the full FAISS index globally and filtering afterwards, this method restricts the search space before computing similarity. It reconstructs stored vectors for matching documents and computes similarity against the query embedding directly.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
query
|
str
|
Search query text. |
required |
mask_node_ids
|
set[str]
|
Set of node_id / node_name values to restrict search to. |
required |
top_k
|
int
|
Number of top results to return. |
10
|
level
|
Level
|
Index level to search. |
'l2'
|
Returns:
| Type | Description |
|---|---|
list[NodeInfo]
|
List of NodeInfo objects sorted by similarity score. |
Source code in codenib/index/embedding/vector_store.py
773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 | |
hierarchical_search
¶
hierarchical_search(
query: str,
l0_top_k: int = 5,
l2_top_k: int = 10,
l0_score_threshold: float | None = None,
l2_score_threshold: float | None = None,
filter_l2_by_l0: bool = True,
) -> dict[str, list[NodeInfo]]
Note: This method is implemented by Claude and is just for future reference. Perform hierarchical search: first L0 (files), then L2 (functions).
This implements a coarse-to-fine retrieval strategy: 1. Search L0 to find relevant files based on their skeletons 2. Search L2 for specific functions/methods 3. Optionally filter L2 results to only include those from L0 files
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
query
|
str
|
Search query text |
required |
l0_top_k
|
int
|
Number of top L0 results (files) |
5
|
l2_top_k
|
int
|
Number of top L2 results (functions/methods) |
10
|
l0_score_threshold
|
float | None
|
Score threshold for L0 results |
None
|
l2_score_threshold
|
float | None
|
Score threshold for L2 results |
None
|
filter_l2_by_l0
|
bool
|
If True, only return L2 results from files found in L0 |
True
|
Returns:
| Type | Description |
|---|---|
dict[str, list[NodeInfo]]
|
Dict with 'l0' and 'l2' keys containing search results |
Source code in codenib/index/embedding/vector_store.py
save
¶
Save the vector store to disk.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | None
|
Path to save the store (uses self.store_path if not provided) |
None
|
Source code in codenib/index/embedding/vector_store.py
load
¶
Load the vector store from disk.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | None
|
Path to load the store from (uses self.store_path if not provided) |
None
|
Source code in codenib/index/embedding/vector_store.py
1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 | |
get_stats
¶
Get statistics about the vector store.
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dictionary with store statistics |
Source code in codenib/index/embedding/vector_store.py
get_embeddings_by_content_hash
¶
Extract raw embedding vectors from the FAISS index, keyed by content hash.
This is used to seed the EmbeddingsCache after a full build so that
the first incremental update achieves ~100% cache hit rate for unchanged
chunks.
Each document's content is MD5-hashed to produce the key. If the
document metadata already contains a content_hash field it is used
directly; otherwise the hash is computed on the fly.
Returns:
| Type | Description |
|---|---|
dict[str, ndarray]
|
Dict mapping content_hash → np.ndarray (float32 vectors). |
Source code in codenib/index/embedding/vector_store.py
rebuild_from_embeddings
¶
Clear level and rebuild its FAISS index from pre-computed embeddings.
Used by the incremental update path: unchanged chunks contribute their cached vectors, so only genuinely new/modified chunks require model inference. No embedding model calls are made by this method.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
documents
|
list
|
Document-like objects with |
required |
embeddings
|
list[ndarray]
|
Corresponding embedding vectors as |
required |
level
|
Level
|
Which index level to rebuild ( |
'l2'
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If documents and embeddings have different lengths. |
Source code in codenib/index/embedding/vector_store.py
delta_update
¶
delta_update(
all_documents: list,
all_embeddings: list[ndarray],
changed_content_hashes: set[str],
level: Level = "l2",
threshold: float = 0.1,
) -> None
Patch the FAISS index in place when the change set is small.
When the fraction of changed chunks is below threshold, this uses
IndexFlat.remove_ids + add to modify only the affected rows,
keeping unchanged vectors and their aligned documents untouched. If
the change ratio exceeds the threshold (or the index is empty), it
falls back to a full rebuild via :meth:rebuild_from_embeddings.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
all_documents
|
list
|
The complete desired set of documents for level
after the update. Must carry |
required |
all_embeddings
|
list[ndarray]
|
Corresponding embedding vectors, aligned with all_documents. |
required |
changed_content_hashes
|
set[str]
|
Content hashes of chunks that were added, removed, or modified in this update cycle. Used both to decide between delta/rebuild and to identify stale rows. |
required |
level
|
Level
|
Which index level to update. |
'l2'
|
threshold
|
float
|
Maximum change ratio (changed/total) for the delta path; above this a full rebuild is performed. |
0.1
|
Source code in codenib/index/embedding/vector_store.py
1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 | |
clear
¶
Clear data from the vector store.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
level
|
Level | None
|
If specified, only clear that level ("l0" or "l2"). If None, clear both levels. |
None
|
Source code in codenib/index/embedding/vector_store.py
build_hierarchical_vector_store
¶
build_hierarchical_vector_store(
*,
repo_path: str,
index_path: str,
plan_name: str | None = None,
languages: list[str] | None = None,
max_lines_per_chunk: int | None = None,
build_levels: list[str] | None = None,
embedding_model: str,
embedding_provider: str,
embedding_dimension: int | None,
embedding_kwargs: dict[str, object] | None = None,
embedding: object | None = None,
index_metric: str = "ip",
index_type: str = "flat",
ivf_nlist: int = 100,
ivf_nprobe: int = 8,
profiler: Profiler | None = None,
force_rebuild: bool = False
) -> CodeVectorStore
Build (or load) a hierarchical vector store (L0/L2) for a repository.
When force_rebuild=False (the default) and a saved index for the
requested embedding_model already exists at index_path, the store
is loaded from disk instead of re-chunking and re-embedding the repository.
Pass force_rebuild=True to unconditionally rebuild.
Source code in codenib/index/embedding/builders.py
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 | |
create_code_vector_store
¶
create_code_vector_store(
embedding_model: str = "text-embedding-ada-002",
embedding_provider: str = "openai",
store_path: str | None = None,
**kwargs
) -> CodeVectorStore
Factory function to create a CodeVectorStore.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
embedding_model
|
str
|
Name of the embedding model |
'text-embedding-ada-002'
|
embedding_provider
|
str
|
Provider for embeddings |
'openai'
|
store_path
|
str | None
|
Path to store/load the vector store |
None
|
**kwargs
|
Additional arguments for CodeVectorStore |
{}
|
Returns:
| Type | Description |
|---|---|
CodeVectorStore
|
CodeVectorStore instance |