Skip to main content

SemanticDht

Struct SemanticDht 

Source
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

Source

pub fn new(config: SemanticDhtConfig) -> Self

Create a new semantic DHT

Source

pub fn register_namespace( &self, namespace: SemanticNamespace, ) -> Result<(), SemanticDhtError>

Register a new semantic namespace

Source

pub fn compute_lsh_hashes( &self, embedding: &[f32], namespace: &NamespaceId, ) -> Result<Vec<LshHash>, SemanticDhtError>

Compute LSH hashes for an embedding

Source

pub fn index_content( &self, cid: Cid, embedding: Vec<f32>, namespace: NamespaceId, ) -> Result<(), SemanticDhtError>

Index content with its embedding

Source

pub fn query( &self, query: SemanticQuery, ) -> Result<Vec<SemanticResult>, SemanticDhtError>

Execute a semantic query

Source

pub fn stats(&self) -> SemanticDhtStats

Get statistics

Source

pub fn get_namespace(&self, id: &NamespaceId) -> Option<SemanticNamespace>

Get namespace information

Source

pub fn list_namespaces(&self) -> Vec<NamespaceId>

List all registered namespaces

Source

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.

Source

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.

Source

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].

Source

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).

Source

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.

Source

pub fn metrics(&self) -> SemanticDhtMetrics

Return a snapshot of routing-quality metrics.

Source

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.

Source

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.

Source

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.

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§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where T: 'a,

Source§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

Source§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where T: 'a,

Source§

fn implicit( self, class: Class, constructed: bool, tag: u32, ) -> TaggedParser<'a, Implicit, Self, E>

Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts 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 more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts 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
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more