pub struct SemanticDht {
pub shard_balancer: Mutex<ShardBalancer>,
/* private fields */
}Expand description
Semantic DHT manager
Fields§
§shard_balancer: Mutex<ShardBalancer>Shard-load balancer: tracks per-peer vector counts and identifies hot-spot peers that should shed load via migration.
Implementations§
Source§impl SemanticDht
impl SemanticDht
Sourcepub fn new(config: SemanticDhtConfig) -> Self
pub fn new(config: SemanticDhtConfig) -> Self
Create a new semantic DHT
Sourcepub fn register_namespace(
&self,
namespace: SemanticNamespace,
) -> Result<(), SemanticDhtError>
pub fn register_namespace( &self, namespace: SemanticNamespace, ) -> Result<(), SemanticDhtError>
Register a new semantic namespace
Sourcepub fn compute_lsh_hashes(
&self,
embedding: &[f32],
namespace: &NamespaceId,
) -> Result<Vec<LshHash>, SemanticDhtError>
pub fn compute_lsh_hashes( &self, embedding: &[f32], namespace: &NamespaceId, ) -> Result<Vec<LshHash>, SemanticDhtError>
Compute LSH hashes for an embedding
Sourcepub fn index_content(
&self,
cid: Cid,
embedding: Vec<f32>,
namespace: NamespaceId,
) -> Result<(), SemanticDhtError>
pub fn index_content( &self, cid: Cid, embedding: Vec<f32>, namespace: NamespaceId, ) -> Result<(), SemanticDhtError>
Index content with its embedding
Sourcepub fn query(
&self,
query: SemanticQuery,
) -> Result<Vec<SemanticResult>, SemanticDhtError>
pub fn query( &self, query: SemanticQuery, ) -> Result<Vec<SemanticResult>, SemanticDhtError>
Execute a semantic query
Sourcepub fn stats(&self) -> SemanticDhtStats
pub fn stats(&self) -> SemanticDhtStats
Get statistics
Sourcepub fn get_namespace(&self, id: &NamespaceId) -> Option<SemanticNamespace>
pub fn get_namespace(&self, id: &NamespaceId) -> Option<SemanticNamespace>
Get namespace information
Sourcepub fn list_namespaces(&self) -> Vec<NamespaceId>
pub fn list_namespaces(&self) -> Vec<NamespaceId>
List all registered namespaces
Sourcepub fn put_with_vector(
&self,
cid: impl Into<String>,
vector: Vec<f32>,
provider_id: impl Into<String>,
) -> Result<(), SemanticDhtError>
pub fn put_with_vector( &self, cid: impl Into<String>, vector: Vec<f32>, provider_id: impl Into<String>, ) -> Result<(), SemanticDhtError>
Store a CID with its embedding vector in the local record store.
The record is validated (dimension check) and then written to the flat
vector_records map. In a full network deployment the caller would
subsequently gossip this record to neighbouring peers.
§Errors
Returns SemanticDhtError::VectorDimensionMismatch when
vector.len() != config.dimension.
Sourcepub fn search_similar(
&self,
query_vector: &[f32],
k: usize,
) -> Result<Vec<(String, f32)>, SemanticDhtError>
pub fn search_similar( &self, query_vector: &[f32], k: usize, ) -> Result<Vec<(String, f32)>, SemanticDhtError>
Return the k CIDs whose stored vectors are most similar to query_vector.
Similarity is measured by cosine similarity (higher = more similar).
Results are returned as (cid_string, similarity_score) pairs in
descending score order.
Expired records (older than config.vector_ttl) are silently excluded.
§Errors
Returns SemanticDhtError::VectorDimensionMismatch when
query_vector.len() != config.dimension.
Sourcepub fn get_routing_convergence(&self) -> f32
pub fn get_routing_convergence(&self) -> f32
Estimate how stable the routing table currently is.
Convergence is modelled as a function of how long the routing table has
been quiescent: the score rises from 0 to 1 over
2 × sync_interval of silence. Once the score crosses
convergence_threshold the table is considered converged.
Returns a value in [0.0, 1.0].
Sourcepub fn efficient_partial_sync(
&self,
peer: &PeerId,
changed_region: &LshHash,
) -> Result<Vec<String>, SemanticDhtError>
pub fn efficient_partial_sync( &self, peer: &PeerId, changed_region: &LshHash, ) -> Result<Vec<String>, SemanticDhtError>
Perform an efficient partial sync with a peer for a specific embedding region.
Only records whose vectors hash to changed_region (via LSH bucket
equivalence) are considered. This avoids the cost of a full index
exchange and is the primary mechanism for keeping distributed vector
indices consistent between peers.
In the current single-node implementation the peer argument is validated and the region is used to filter the local record set; the function returns the set of CIDs that would be sent to the peer in a real network exchange.
§Errors
Returns SemanticDhtError::PeerUnreachable when peer is the zero
peer ID (used as a sentinel for “invalid peer” in tests).
Sourcepub fn efficient_partial_sync_with_config(
&self,
peer: &PeerId,
changed_region: &LshHash,
config: &PartialSyncConfig,
prev_vectors: Option<&HashMap<String, Vec<f32>>>,
) -> Result<(Vec<String>, PartialSyncStats), SemanticDhtError>
pub fn efficient_partial_sync_with_config( &self, peer: &PeerId, changed_region: &LshHash, config: &PartialSyncConfig, prev_vectors: Option<&HashMap<String, Vec<f32>>>, ) -> Result<(Vec<String>, PartialSyncStats), SemanticDhtError>
Enhanced efficient partial sync with configurable threshold, batching, and round tracking.
Only gossips vectors whose embedding changed by more than
config.sync_threshold (cosine distance) since the last known state
stored in prev_vectors (a CID → previous vector snapshot).
Messages are batched up to config.batch_size per GossipSub batch.
round_number is compared against config.max_rounds to detect
divergence; if round_number >= config.max_rounds the caller should
trigger a full resync (this function still executes normally but the
returned stats will reflect the round count).
Returns the list of CIDs that would be sent plus sync statistics.
Sourcepub fn metrics(&self) -> SemanticDhtMetrics
pub fn metrics(&self) -> SemanticDhtMetrics
Return a snapshot of routing-quality metrics.
Sourcepub fn rebalance_if_needed(&self) -> Vec<(String, String)>
pub fn rebalance_if_needed(&self) -> Vec<(String, String)>
Check whether any peer in the shard balancer is overloaded and, if so,
return the list of (cid, from_peer) migration candidates.
Returns an empty Vec when the cluster is already balanced.
Sourcepub fn merge_partial_index(
&self,
records: Vec<VectorAnnotatedRecord>,
source_peer: &str,
) -> MergeResult
pub fn merge_partial_index( &self, records: Vec<VectorAnnotatedRecord>, source_peer: &str, ) -> MergeResult
Merge a partial index received from source_peer into the local record
store.
For each incoming VectorAnnotatedRecord:
- Added – CID not yet known locally → insert.
- Updated – CID known but the incoming record has a strictly longer
ttl_secs(a proxy for freshness when wall-clock timestamps are unavailable) → overwrite. - Skipped – CID known and local copy is as fresh or fresher.
- Conflict – CID known but vector dimensions do not match → neither copy is overwritten; the conflict counter is incremented so the caller can log or raise an alert.
The source_peer argument is recorded in the provider_id field of any
inserted/updated records, allowing provenance tracking.
Sourcepub fn evict_expired_records(&self)
pub fn evict_expired_records(&self)
Evict vector records that have exceeded their TTL.
Call this periodically (e.g. at sync_interval) to bound memory usage.
Sourcepub async fn distributed_search(
&self,
query: &[f32],
top_k: usize,
timeout_ms: u64,
) -> Result<Vec<SearchResult>, SemanticDhtError>
pub async fn distributed_search( &self, query: &[f32], top_k: usize, timeout_ms: u64, ) -> Result<Vec<SearchResult>, SemanticDhtError>
Query the semantic DHT across the local shard.
In a fully distributed deployment this method would fan out top_k
sub-queries to each peer responsible for the relevant LSH bucket, merge
the partial results, and apply timeout_ms. In the current single-node
implementation it searches the local vector_records store and tags
every result with peer = None (local).
Results are sorted by descending cosine similarity score.
§Errors
Returns SemanticDhtError::VectorDimensionMismatch when
query.len() != config.dimension.
Auto Trait Implementations§
impl !Freeze for SemanticDht
impl !RefUnwindSafe for SemanticDht
impl !UnwindSafe for SemanticDht
impl Send for SemanticDht
impl Sync for SemanticDht
impl Unpin for SemanticDht
impl UnsafeUnpin for SemanticDht
Blanket Implementations§
Source§impl<'a, T, E> AsTaggedExplicit<'a, E> for Twhere
T: 'a,
impl<'a, T, E> AsTaggedExplicit<'a, E> for Twhere
T: 'a,
Source§impl<'a, T, E> AsTaggedImplicit<'a, E> for Twhere
T: 'a,
impl<'a, T, E> AsTaggedImplicit<'a, E> for Twhere
T: 'a,
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
Source§impl<T> Instrument for T
impl<T> Instrument for T
Source§fn instrument(self, span: Span) -> Instrumented<Self>
fn instrument(self, span: Span) -> Instrumented<Self>
Source§fn in_current_span(self) -> Instrumented<Self>
fn in_current_span(self) -> Instrumented<Self>
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self>
fn into_either(self, into_left: bool) -> Either<Self, Self>
self into a Left variant of Either<Self, Self>
if into_left is true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
self into a Left variant of Either<Self, Self>
if into_left(&self) returns true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read more