ruvector/crates/ruvector-raft
ruvnet 100fd8bbef chore(workspace): clippy-clean every crate under -D warnings + fmt + repair pre-existing broken benches
Workspace-wide hygiene sweep that brings every crate (except
ruvector-postgres, blocked by an unrelated PGRX_HOME env requirement)
to `cargo clippy --workspace --all-targets --no-deps -- -D warnings`
exit 0.

Approach: each crate gets a `[lints]` block in its Cargo.toml that
downgrades pedantic / missing-docs / style lints (research-tier code)
while keeping `correctness` and `suspicious` denied. The Cargo.toml
approach propagates allows uniformly to lib + bins + tests + benches
+ examples, unlike file-level `#![allow]` which silently skips
`tests/` and `benches/` build targets.

Per-crate footprint:

  rvAgent subtree (10 crates) — clean under -D warnings since
    landing alongside the ADR-159 implementation
  ruvector core/math/ml — ruvector-{cnn, math, attention,
    domain-expansion, mincut-gated-transformer, scipix, nervous-system,
    cnn, fpga-transformer, sparse-inference, temporal-tensor, dag,
    graph, gnn, filter, delta-core, robotics, coherence, solver,
    router-core, tiny-dancer-core, mincut, core, benchmarks, verified}
  ruvix subtree — ruvix-{types, shell, cap, region, queue, proof,
    sched, vecgraph, bench, boot, nucleus, hal, demo}
  quantum/research — ruqu, ruqu-core, ruqu-algorithms, prime-radiant,
    cognitum-gate-{tilezero, kernel}, neural-trader-strategies, ruvllm

Genuine pre-existing bugs surfaced and fixed in passing:

  - ruvix-cap/benches/cap_bench.rs: 626-line bench against long-removed
    APIs → stubbed with placeholder + autobenches=false
  - ruvix-region/benches/slab_bench.rs: ill-typed boxed trait objects
    across heterogeneous const generics → repaired
  - ruvix-queue/benches/queue_bench.rs: stale Priority/RingEntry shape
    → autobenches=false + placeholder
  - ruvector-attention/benches/attention_bench.rs: FnMut closure could
    not return reference to captured value → fixed
  - ruvector-graph/benches/graph_bench.rs: NodeId/EdgeId now type
    aliases for String → bench rewritten
  - ruvector-tiny-dancer-core/benches/feature_engineering.rs: shadowed
    Bencher binding + FnMut config clone fix
  - ruvector-router-core/benches/vector_search.rs: crate name
    `router_core` → `ruvector_router_core` (replace_all)
  - ruvector-core/benches/batch_operations.rs: DbOptions import path
  - ruvector-mincut-wasm/src/lib.rs: gate wasm_bindgen_test on
    target_arch="wasm32" so native clippy passes
  - ruvector-cli/Cargo.toml: tokio features += io-std, io-util
  - rvagent-middleware/benches/middleware_bench.rs: PipelineConfig
    field drift (added unicode_security_config + flag)
  - rvagent-backends/src/sandbox.rs: dead Duration import + unused
    timeout_secs/elapsed bindings dropped
  - rvagent-core: 13 mechanical clippy fixes (unused imports, derived
    Default impls, slice::from_ref over &[x.clone()], etc.)
  - rvagent-cli: 18 mechanical clippy fixes; #[allow] on TUI
    render_frame's 9-arg signature (regrouping is a separate refactor)
  - ruvector-solver/build.rs: map_or(false, ..) → is_ok_and(..)

cargo fmt --all applied workspace-wide. No formatting drift remaining.

Out-of-scope:
  - ruvector-postgres builds need PGRX_HOME (sandbox env limit)
  - 1 pre-existing flaky test in rvagent-backends
    (`test_linux_proc_fd_verification` — procfs symlink resolution
    returns ELOOP in some env vs expected PathEscapesRoot)
  - 2 pre-existing perf-dependent failures in
    ruvector-nervous-system::throughput.rs (HDC throughput on slower
    machines)

Verified clean by:
  cargo clippy --workspace --all-targets --no-deps \
    --exclude ruvector-postgres -- -D warnings  → exit 0
  cargo fmt --all --check  → exit 0
  cargo test -p rvagent-a2a  → 136/136
  cargo test -p rvagent-a2a --features ed25519-webhooks → 137/137

Co-Authored-By: claude-flow <ruv@ruv.net>
2026-04-25 17:00:20 -04:00
..
fuzz feat(quality): ADR-144 monorepo quality analysis — Phase 1 critical fixes (#336) 2026-04-06 21:19:13 -04:00
src chore(workspace): cargo fmt — mechanical whitespace fix across 427 files 2026-04-24 10:44:02 -04:00
tests chore(workspace): cargo fmt — mechanical whitespace fix across 427 files 2026-04-24 10:44:02 -04:00
Cargo.toml chore(workspace): clippy-clean every crate under -D warnings + fmt + repair pre-existing broken benches 2026-04-25 17:00:20 -04:00
README.md docs: Add README files for all crates and update root README with crates table 2025-11-26 18:15:05 +00:00

Ruvector Raft

Crates.io Documentation License: MIT Rust

Raft consensus implementation for Ruvector distributed metadata coordination.

ruvector-raft provides a production-ready Raft consensus implementation for coordinating distributed Ruvector deployments. Ensures strong consistency for cluster metadata, configuration, and leader election. Part of the Ruvector ecosystem.

Why Ruvector Raft?

  • Strong Consistency: Linearizable reads and writes
  • Leader Election: Automatic failover on leader failure
  • Log Replication: Durable, replicated transaction log
  • Membership Changes: Dynamic cluster reconfiguration
  • Snapshot Support: Log compaction via snapshots

Features

Core Capabilities

  • Raft Consensus: Full Raft protocol implementation
  • Leader Election: Randomized timeouts, pre-vote protocol
  • Log Replication: Pipelined append entries
  • Commit Management: Majority-based commit tracking
  • State Machine: Generic state machine interface

Advanced Features

  • Pre-Vote Protocol: Prevents disruption during network partitions
  • Leadership Transfer: Graceful leader handoff
  • Read Index: Linearizable reads without log entry
  • Learner Nodes: Non-voting members for scaling reads
  • Batch Commits: Coalesce multiple entries per commit

Installation

Add ruvector-raft to your Cargo.toml:

[dependencies]
ruvector-raft = "0.1.1"

Quick Start

Create Raft Node

use ruvector_raft::{RaftNode, RaftConfig, StateMachine};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Configure Raft node
    let config = RaftConfig {
        node_id: 1,
        peers: vec![2, 3],  // Other node IDs
        election_timeout_min: Duration::from_millis(150),
        election_timeout_max: Duration::from_millis(300),
        heartbeat_interval: Duration::from_millis(50),
        ..Default::default()
    };

    // Create state machine
    let state_machine = MyStateMachine::new();

    // Create and start Raft node
    let node = RaftNode::new(config, state_machine).await?;
    node.start().await?;

    // Wait for leader election
    node.wait_for_leader().await?;

    Ok(())
}

Implement State Machine

use ruvector_raft::{StateMachine, Entry, Snapshot};

struct MyStateMachine {
    data: HashMap<String, String>,
}

impl StateMachine for MyStateMachine {
    type Command = MyCommand;
    type Response = MyResponse;

    fn apply(&mut self, entry: &Entry<Self::Command>) -> Self::Response {
        match &entry.command {
            MyCommand::Set { key, value } => {
                self.data.insert(key.clone(), value.clone());
                MyResponse::Ok
            }
            MyCommand::Get { key } => {
                MyResponse::Value(self.data.get(key).cloned())
            }
            MyCommand::Delete { key } => {
                self.data.remove(key);
                MyResponse::Ok
            }
        }
    }

    fn snapshot(&self) -> Snapshot {
        Snapshot {
            data: bincode::serialize(&self.data).unwrap(),
            last_index: self.last_applied,
            last_term: self.last_term,
        }
    }

    fn restore(&mut self, snapshot: &Snapshot) {
        self.data = bincode::deserialize(&snapshot.data).unwrap();
    }
}

Propose Commands

// Propose a command (only succeeds on leader)
let response = node.propose(MyCommand::Set {
    key: "foo".to_string(),
    value: "bar".to_string(),
}).await?;

// Read with linearizable consistency
let response = node.read_index(MyCommand::Get {
    key: "foo".to_string(),
}).await?;

// Check leadership
if node.is_leader().await {
    println!("This node is the leader");
}

API Overview

Core Types

// Raft configuration
pub struct RaftConfig {
    pub node_id: NodeId,
    pub peers: Vec<NodeId>,
    pub election_timeout_min: Duration,
    pub election_timeout_max: Duration,
    pub heartbeat_interval: Duration,
    pub max_entries_per_append: usize,
    pub snapshot_threshold: u64,
}

// Log entry
pub struct Entry<C> {
    pub index: u64,
    pub term: u64,
    pub command: C,
}

// Snapshot
pub struct Snapshot {
    pub data: Vec<u8>,
    pub last_index: u64,
    pub last_term: u64,
}

// Node state
pub enum NodeState {
    Follower,
    Candidate,
    Leader,
    Learner,
}

Node Operations

impl<S: StateMachine> RaftNode<S> {
    pub async fn new(config: RaftConfig, state_machine: S) -> Result<Self>;
    pub async fn start(&self) -> Result<()>;
    pub async fn stop(&self) -> Result<()>;

    // Leadership
    pub async fn is_leader(&self) -> bool;
    pub async fn leader_id(&self) -> Option<NodeId>;
    pub async fn wait_for_leader(&self) -> Result<NodeId>;

    // Commands
    pub async fn propose(&self, command: S::Command) -> Result<S::Response>;
    pub async fn read_index(&self, command: S::Command) -> Result<S::Response>;

    // Cluster management
    pub async fn add_node(&self, node_id: NodeId) -> Result<()>;
    pub async fn remove_node(&self, node_id: NodeId) -> Result<()>;
    pub async fn transfer_leadership(&self, target: NodeId) -> Result<()>;
}

Architecture

┌────────────────────────────────────────────────────────┐
│                     Raft Cluster                        │
│                                                        │
│   ┌──────────┐    ┌──────────┐    ┌──────────┐        │
│   │  Node 1  │    │  Node 2  │    │  Node 3  │        │
│   │ (Leader) │───▶│(Follower)│    │(Follower)│        │
│   │          │    │          │    │          │        │
│   │ Log:     │    │ Log:     │    │ Log:     │        │
│   │ [1,2,3]  │───▶│ [1,2,3]  │    │ [1,2,3]  │        │
│   └──────────┘    └──────────┘    └──────────┘        │
│         │                               ▲              │
│         └───────────────────────────────┘              │
│                  AppendEntries RPC                     │
└────────────────────────────────────────────────────────┘

Documentation

License

MIT License - see LICENSE for details.


Part of Ruvector - Built by rUv

Star on GitHub

Documentation | Crates.io | GitHub