HNSW, pgvector and the Vector Service
Vectors reach the engine by two routes. The SQL route is pgvector compatible: VECTOR(n) columns, distance operators, and CREATE INDEX ... USING hnsw. The second route is the wire-neutral vector service in src/vector/, which keeps named collections, can index rows from several wires at once, and is called from SQL through vector_search(...) and from wire-specific vector features. Both use the HNSW graph in src/index/hnsw.rs. Embedders are on Embeddings; index choice is on Overview.
VECTOR(n) columns
A vector(n) column stores the vector's canonical pgvector text, such as [1,2,3], as a string value. On write, the value is parsed, checked and reformatted by pgvector::cast. (source: src/query/engine.rs, coerce_assign_value_inner; src/query/pgvector.rs, cast) The engine also has a binary Value::Vector type (an f32 array with a cached norm that is not serialized), but the SQL column path stores text. (source: src/types/value.rs, Value::Vector; src/types/vector.rs, Vector)
Input checks:
| Check | Result |
|---|---|
More than 16000 dimensions (MAX_DIM) |
Error |
| Empty vector, NaN or infinity | Error, SQLSTATE 22000 |
| Malformed text | Error, SQLSTATE 22P02 |
Dimension differs from vector(n)
|
Error (check_dims) |
(source: src/query/pgvector.rs, parse, check_dims, vector_typmod, is_data_exception) Test: io_and_errors. (source: src/query/pgvector.rs, io_and_errors)
Distance operators and functions
| Operator | Function | Distance |
|---|---|---|
<-> |
l2_distance |
Euclidean |
<=> |
cosine_distance |
1 minus cosine similarity; NaN if either norm is zero |
<#> |
vector_negative_inner_product |
Negative inner product |
<+> |
l1_distance |
Manhattan |
| none | inner_product |
Inner product |
(source: src/query/pgvector.rs, distance, l2_distance, cosine_distance, inner_product, negative_inner_product, l1_distance)
Sums use four lanes reduced as (l0+l2)+(l1+l3), with the final steps in f64, to match pgvector's results. (source: src/query/pgvector.rs, lane_sum) Other functions: vector_dims, vector_norm, l2_normalize, binary_quantize, subvector, casts to real[], element-wise +, -, *, concatenation, comparison, and avg/sum aggregates. (source: src/query/pgvector.rs, those functions) Test: ops_and_functions. (source: src/query/pgvector.rs, ops_and_functions)
The graph code uses a separate distance implementation on Vector:
DistanceMetric |
Value |
|---|---|
L2 |
Square root of the sum of squares, 8 accumulators |
Cosine (the default) |
1 minus clamped similarity; similarity 0 when a norm is below EPSILON
|
InnerProduct |
Negative dot product |
Manhattan |
L1 |
Hamming |
Count of positions with differing sign |
(source: src/types/vector.rs, DistanceMetric, Vector::distance) Tests: test_l2_distance, test_cosine_similarity, test_normalize. (source: src/types/vector.rs, tests)
The HNSW graph (src/index/hnsw.rs)
Structure and parameters
| Parameter | Default |
|---|---|
M (links per node above layer 0) |
16 (DEFAULT_M) |
M_max0 (links at layer 0) |
32 (DEFAULT_M_MAX0) |
ef_construction |
200 (DEFAULT_EF_CONSTRUCTION) |
ef (search) |
50 (DEFAULT_EF); a search uses max(ef, k)
|
Level multiplier ml
|
1 / ln(M) |
| Maximum level | 16 |
(source: src/index/hnsw.rs, constants, HnswIndex::search) Neighbour selection uses the diversity heuristic with pruned connections kept to fill the list. (source: src/index/hnsw.rs, neighbour selection)
Operations
| Operation | Behaviour |
|---|---|
insert |
Holds the node list write lock for the whole insert |
insert_flat |
Adds the vector with no graph links (exact mode) |
insert_parallel |
First 10,000 records inserted serially (SERIAL_FIRST), the rest in parallel batches |
delete |
Marks the node deleted, removes its edges, gives each former neighbour a repair link to its nearest other former neighbour, picks a new entry point if needed, and puts the slot on a free list for reuse |
search |
Read lock on the node list |
search_with_filter |
Search with a record filter |
exact_top_k |
Bounded max-heap over all vectors, deterministic tie order |
link_unreachable |
Links any node no search can reach |
export, from_parts
|
Copy the graph out and rebuild it, used by the vector service's graph files |
save, load
|
bincode HnswState; not used by the SQL path |
(source: src/index/hnsw.rs, those functions)
Tests: insert_reuses_search_buffers, test_hnsw_insert_search, test_hnsw_exact_match, test_hnsw_dimension_mismatch, test_hnsw_delete, link_unreachable_leaves_no_node_unreachable, deletes_keep_the_rest_findable, parallel_insert_finds_every_record, parallel_insert_resumes_a_restored_graph. (source: src/index/hnsw.rs, tests) Criterion benchmarks hnsw_benchmark and distance_benchmark are in benches/vector_bench.rs. (source: benches/vector_bench.rs)
SQL KNN: CREATE INDEX ... USING hnsw
Creating the index
USING hnsw (or ivfflat) on one column writes __catalog__:vecindex:{table}:{name} with the column and a metric tag, then backfills an entry in the VectorIndexRegistry. (source: src/query/engine.rs, execute_create_index, build_vector_index_entry)
| Operator class | Metric |
|---|---|
vector_l2_ops (or none) |
L2 |
vector_cosine_ops |
Cosine |
vector_ip_ops |
Inner product |
vector_l1_ops |
Manhattan |
(source: src/query/sql/parser.rs, operator class mapping) WITH (m = ..., ef_construction = ...) is parsed and ignored, and ivfflat's lists is ignored; the graph always uses the defaults above. (source: src/query/sql/parser.rs, CREATE INDEX parsing; src/query/engine.rs, build_vector_index_entry)
A VectorIndexEntry holds the graph, maps between graph ids and row keys, a count of retired vectors, the metric, the dimension, a dirty flag and a flat flag. (source: src/storage/mod.rs, VectorIndexEntry)
Exact mode for small tables
At or below SYNERGYDB_VECTOR_EXACT_MAXROWS rows (default 50,000) the entry is built flat, with no graph links, and queries rank every vector with exact_top_k. SYNERGYDB_VECTOR_EXACT=1 forces exact search at any size. (source: src/query/engine.rs, build_vector_index_entry, try_hnsw_candidate_keys)
When the index is used
try_hnsw_candidate_keys returns candidates only when all of these hold:
- the query is not inside an explicit transaction;
- the plan is
ORDER BY col <op> constascending with one sort key and aLIMIT n; - the operator maps to a metric (
<->L2,<=>cosine,<#>inner product,<+>Manhattan) and avecindexdefinition exists for that column and metric; - the entry is not dirty, its dimension matches the query vector, and it holds at least
nvectors.
(source: src/query/engine.rs, try_hnsw_candidate_keys) An index built for one metric is not used for another; test hnsw_l2_index_orders_by_l2_not_cosine. (source: src/query/engine.rs, hnsw_l2_index_orders_by_l2_not_cosine)
Search, filtering and re-ranking
The engine fetches max(n * 8, floor) candidates from the graph (VECTOR_OVERFETCH = 8). The floor is VECTOR_MIN_FETCH = 256, which SYNERGYDB_HNSW_EF_SEARCH or the session setting SET hnsw.ef_search can change (minimum 16). (source: src/query/engine.rs, VECTOR_OVERFETCH, VECTOR_MIN_FETCH, try_hnsw_candidate_keys)
With a WHERE clause the engine evaluates the filter on the candidates and, if fewer than n pass, widens the fetch four times over and searches again, until n rows pass or the whole index has been ranked. (source: src/query/engine.rs, try_hnsw_candidate_keys) Test: hnsw_filtered_knn_matches_brute_force_and_uses_index. (source: src/query/engine.rs, that test)
The candidate keys restrict the table scan (vector_scan_restrict); the base rows are refetched and the unchanged Sort and Limit rank them by exact distance computed with pgvector::distance. Graph approximation can therefore only drop a true neighbour, never misorder the returned rows. (source: src/query/engine.rs, vector_scan_restrict, try_hnsw_candidate_keys) Tests: hnsw_l2_topk_matches_brute_force_exactly, hnsw_accelerated_path_is_actually_used, hnsw_non_accelerated_paths_unaffected, hnsw_cosine_opclass_plumbs_metric, hnsw_scale_report. (source: src/query/engine.rs, those tests)
Maintenance on write
| Event | Effect |
|---|---|
Autocommit INSERT
|
Vector added to the graph (vector_registry_on_insert) |
Autocommit UPDATE or DELETE
|
Old vector retired in place, new one inserted (vector_registry_on_row_write); a graph entry is marked dirty once retired vectors exceed a quarter of live ones |
| Other writes | Entry marked dirty (vector_registry_mark_dirty) |
| Transaction commit | Entries for every touched table marked dirty |
| Next query on a dirty entry, or a dimension change | Full rebuild from a table scan |
(source: src/query/engine.rs, vector_registry_on_insert, vector_registry_on_row_write, vector_registry_mark_dirty) Rows whose value is a Value::Vector or [...] text are indexed; others are skipped. (source: src/query/engine.rs, cell_as_vector) Tests: hnsw_backfill_and_incremental_insert, hnsw_update_delete_maintained_in_place, hnsw_delete_removes_row_from_results. (source: src/query/engine.rs, those tests)
The registry is in memory only and is rebuilt after a restart on first use. (source: src/storage/mod.rs, VectorIndexEntry)
Differences from the guide
How it works says, citing a 2026-11-24 status entry, that a pgvector KNN query with a WHERE clause falls back to brute force. In the snapshot the filtered path uses the index with widening; only queries inside a transaction are always brute force. (source: src/query/engine.rs, try_hnsw_candidate_keys)
The vector service (src/vector/)
Collections and storage
| Key | Contents |
|---|---|
__vector__:c:{db}\x1f{name} |
Collection definition (JSON CollectionDef) |
__vector__:v:{db}\x1f{name}\x1f{source}\x1f{id} |
Record: dimension as u32 LE, f32 LE values, payload JSON |
(source: src/vector/mod.rs, key builders, record encoding) Collections load lazily on first use, one loader at a time, with a streamed scan. (source: src/vector/mod.rs, collection loading)
| Type | Values |
|---|---|
IndexKind |
Flat, or Hnsw { m, ef_construction } (default m 16, ef_construction 128) |
Owner |
Postgres, Redis, Elasticsearch, MongoDb, Neo4j, Cassandra, CrossWire, Other
|
Filter |
Eq, Ne, In, Nin, Gt, Gte, Lt, Lte, Exists, And, Or, Not, Refs
|
(source: src/vector/mod.rs, IndexKind, Owner, Filter)
| Constant | Value |
|---|---|
EXACT_MAX_ROWS |
10,000 |
MIN_EF_CONSTRUCTION |
128 |
ORPHANS_MAX |
4096 |
GRAPH_SAVE_EVERY |
300 s |
GRAPH_FILE_VERSION |
1 |
REACH_CHECK_MAX |
16 |
(source: src/vector/mod.rs, constants)
Background graph build
A collection with more than 10,000 records and no graph, or with more retired records than live ones, starts a build on a vector-graph thread using insert_parallel. It uses half the cores unless SYNERGYDB_VECTOR_BUILD_THREADS is set. Writes during the build are queued and replayed before the new graph is swapped in; searches meanwhile use an exact scan. (source: src/vector/mod.rs, graph build, pending) A cosine collection builds its graph with inner product on unit-normalized vectors. (source: src/vector/mod.rs, graph metric selection)
During a first build the partial graph is saved every SYNERGYDB_VECTOR_PARTIAL_SAVE_SECS (default 600) and the build resumes after a restart. (source: src/vector/mod.rs, partial save) Tests: searches_answer_while_the_graph_builds, partial_graph_build_resumes_after_restart, stale_partial_graph_is_rebuilt. (source: src/vector/tests.rs, those tests)
Graph files
The graph is saved to <data_dir>/vector_graphs/<hex(db\x1fname)>.graph as a bincode SavedGraph, written to a temporary file and renamed. When an at-rest keyring is configured the file is sealed and starts with the magic \0SDB-VGRAPHSEAL1. (source: src/vector/mod.rs, SavedGraph, GRAPH_SEAL_MAGIC)
restore_graph rejects a file whose settings do not match the collection. If fewer than three quarters of records are placed it continues the partial build, or rebuilds when stale entries exceed a quarter of placed ones. Records not in the graph go to a catch-up list that is added in the background. (source: src/vector/mod.rs, restore_graph) Tests: search_graph_survives_restart, survives_restart. (source: src/vector/tests.rs, those tests)
Search
SearchRequest.num_candidates defaults to max(k, 40). With a graph, the service searches with that ef, then re-ranks every candidate exactly together with orphans (records the reach check found unreachable, up to 4096), catch-up records and exact duplicates of the query vector. With a filter, it switches to an exact scan when the allowed record count is at most min(10,000, ef * 20). Exact scans run in parallel above 50,000 records on half the cores, clamped to 1 to 8 threads. Ties are ordered by document reference. (source: src/vector/mod.rs, search, SearchRequest)
A put of an existing vector with a new payload updates in place. A live write runs a k = 1 reach check and records an unreachable record as an orphan. (source: src/vector/mod.rs, put)
Tests: exact_knn_all_metrics, upsert_replaces_and_delete_removes, dimension_and_duplicate_errors, filters, hnsw_recall_matches_exact, product_scores, fresh_inserts_are_found_by_graph_search, exact_vector_always_finds_its_record. (source: src/vector/tests.rs, those tests)
Cross-wire collections (src/vector/sources.rs)
Sources
SourceSpec |
Reads | Defaults |
|---|---|---|
Sql (aliases postgres, mysql) |
Table rows | Database postgres
|
Mongodb |
Collection documents | Database test
|
Redis |
Hashes under a key prefix | |
Elasticsearch |
Index documents, from the __es__:doc: journal |
(source: src/vector/sources.rs, SourceSpec) Collections live in the database _crosswire (GLOBAL_DB). A source names either text fields (embedded by the collection's embedder) or a vector field. (source: src/vector/sources.rs, GLOBAL_DB, create_collection) Test: redis_source_skips_other_keys_unread. (source: src/vector/tests.rs)
Creating a collection
| Spec field | Accepted values | Default |
|---|---|---|
metric |
cosine/cos, l2/euclidean, ip/inner_product/dot/dot_product/dotproduct, l1/manhattan
|
cosine |
index |
flat or exact for Flat; anything else Hnsw
|
Hnsw |
m |
integer | 16 |
ef_construction |
integer, raised to at least 128 | 64, so 128 in effect |
(source: src/vector/sources.rs, create_collection) Text sources need an embedder. An OpenAI-style embedder with dims 0 is probed with the text "dimension probe" to learn its dimension. if_not_exists on an existing collection returns it without re-indexing. (source: src/vector/sources.rs, create_collection)
The background indexer
A WriteWatcher (on_keys, on_range) sends write notifications over a crossbeam-channel queue to a vector-indexer thread, which drains up to 1024 messages per batch. Each affected collection is rescanned: ranges are re-read for SQL and MongoDB sources; other sources get a full rescan. (source: src/vector/sources.rs, WriteWatcher, indexer loop)
| Step | Detail |
|---|---|
| Read | In chunks of 1024 (RESCAN_CHUNK), applying live writes between chunks |
| Skip unchanged | A content hash stored as _h
|
| Payload | Adds _wire, _source, _id
|
| Embed | 64 texts per call |
| Write | 64 records per lock when the graph is ready, 4096 otherwise; upserts in batches of 512 |
| Final sweep | Deletes records whose source rows are gone |
(source: src/vector/sources.rs, rescan and apply functions) sync(timeout) waits until the queued and done counters meet. resume() runs at server start and backfills every collection. (source: src/vector/sources.rs, sync, resume; src/server/mod.rs, startup)
Indexer phases
The indexer labels its work with heap::phase so the memory log can attribute allocations:
| Phase label |
|---|
vector indexer: re-index |
range re-read |
read sql, read mongodb, read redis, read elasticsearch
|
read redis ops, read redis hash
|
embed |
vector store write, vector graph insert (in src/vector/mod.rs) |
(source: src/vector/sources.rs, heap::phase calls; src/vector/mod.rs, heap::phase calls) The phases appear in the memory log only when SYNERGYDB_MEMORY_LOG_SECS is set. (source: docs/status/2026-11-30-vector-indexer-phases.md)
Not verified: no test checks the phase labels.
SQL functions
| Function | Purpose |
|---|---|
vector_collection_create(name, spec_json, if_not_exists) |
Create a cross-wire collection |
vector_collection_drop(name) |
Drop it |
vector_collection_sync(ms) |
Wait for the indexer (default 60000 ms) |
embed(text [, collection]) |
Embed text with the default or the collection's embedder |
vector_search(collection, query, k, filter) |
Returns wire, source, id, distance, score, payload; k defaults to 10, filter is jsonb
|
(source: src/vector/sources.rs, sql_handles, sql_call, sql_search) score is 1 - d for cosine, -d for inner product, and 1 / (1 + d) for L2 and L1. Filters accept $eq, $ne, $in, $nin, $gt, $gte, $lt, $lte, $exists, $not, $and, $or, $nor. (source: src/vector/sources.rs, sql_search, filter parsing) Test: mongo_style_filters_parse. (source: src/vector/tests.rs)
REST and gRPC vector search
The REST route /api/v1/vectors/search, the advanced vector search route and the gRPC VectorSearch method build a SQL string that calls vector_distance(...), with the table and column names placed into the string. (source: src/protocol/http/routes.rs, vector search handlers; src/protocol/grpc/service.rs, VectorSearch)
Not verified: no vector_distance SQL function is defined in src/query/, so these routes likely return an error. No test exercises them against a running engine. The guide's HTTP and GraphQL page lists the REST surface as Preview.
Status entry notes
The 2026-11-27 status entry on background graph builds describes a limit of a quarter of the collection for some step; the code and the 2026-11-28 parallel-build entry describe the build placing as many records as the collection holds. The code is described above. (source: docs/status/2026-11-27-vector-graph-background.md, docs/status/2026-11-28-vector-graph-parallel-build.md, src/vector/mod.rs)