shodh-memory 0.2.0

Persistent cognitive memory for AI agents and robots — Hebbian learning, knowledge graph, spatial recall. Zenoh/ROS2 native. Single binary, runs offline.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
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
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
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
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
//! Circuit breaker pattern for embedding service resilience
//!
//! Implements a production-grade circuit breaker to prevent cascading failures
//! when the ONNX embedding service is degraded or unavailable.
//!
//! # States
//! - **Closed**: Normal operation, requests pass through
//! - **Open**: Service is failing, requests are rejected immediately
//! - **HalfOpen**: Testing if service has recovered
//!
//! # Configuration
//! - `failure_threshold`: Number of failures before opening (default: 5)
//! - `success_threshold`: Successes needed to close from half-open (default: 2)
//! - `open_duration`: Time circuit stays open before testing (default: 30s)
//!
//! # Metrics Integration
//! All state transitions and rejections are tracked via Prometheus metrics.

use anyhow::Result;
use parking_lot::Mutex;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;
use std::time::{Duration, Instant};

use super::{minilm::MiniLMEmbedder, Embedder};

/// Circuit breaker states
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CircuitState {
    /// Normal operation - requests pass through
    Closed,
    /// Service is failing - requests rejected immediately
    Open,
    /// Testing recovery - limited requests allowed
    HalfOpen,
}

impl std::fmt::Display for CircuitState {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            CircuitState::Closed => write!(f, "closed"),
            CircuitState::Open => write!(f, "open"),
            CircuitState::HalfOpen => write!(f, "half_open"),
        }
    }
}

/// Circuit breaker configuration
#[derive(Debug, Clone)]
pub struct CircuitBreakerConfig {
    /// Number of consecutive failures before opening the circuit
    pub failure_threshold: u32,
    /// Number of consecutive successes needed to close from half-open
    pub success_threshold: u32,
    /// Duration the circuit stays open before transitioning to half-open
    pub open_duration: Duration,
    /// Maximum time to wait for a single embedding operation
    pub call_timeout: Duration,
}

impl Default for CircuitBreakerConfig {
    fn default() -> Self {
        Self {
            failure_threshold: 5,
            success_threshold: 2,
            open_duration: Duration::from_secs(30),
            call_timeout: Duration::from_secs(10),
        }
    }
}

/// Internal state tracking
struct CircuitBreakerState {
    state: CircuitState,
    consecutive_failures: u32,
    consecutive_successes: u32,
    last_failure_time: Option<Instant>,
    last_state_change: Instant,
}

impl CircuitBreakerState {
    fn new() -> Self {
        Self {
            state: CircuitState::Closed,
            consecutive_failures: 0,
            consecutive_successes: 0,
            last_failure_time: None,
            last_state_change: Instant::now(),
        }
    }
}

/// Circuit breaker wrapper for embedding service
///
/// Provides resilience by:
/// 1. Tracking failure rates
/// 2. Opening circuit when failures exceed threshold
/// 3. Automatically testing recovery after cooldown
/// 4. Falling back to simplified embeddings when circuit is open
pub struct ResilientEmbedder {
    inner: Arc<MiniLMEmbedder>,
    config: CircuitBreakerConfig,
    state: Mutex<CircuitBreakerState>,
    // Atomic counters for metrics (lock-free)
    total_calls: AtomicU64,
    total_rejections: AtomicU64,
    total_fallbacks: AtomicU64,
}

impl ResilientEmbedder {
    /// Create a new resilient embedder wrapping the given MiniLM embedder
    pub fn new(embedder: Arc<MiniLMEmbedder>, config: CircuitBreakerConfig) -> Self {
        Self {
            inner: embedder,
            config,
            state: Mutex::new(CircuitBreakerState::new()),
            total_calls: AtomicU64::new(0),
            total_rejections: AtomicU64::new(0),
            total_fallbacks: AtomicU64::new(0),
        }
    }

    /// Create with default configuration
    pub fn with_defaults(embedder: Arc<MiniLMEmbedder>) -> Self {
        Self::new(embedder, CircuitBreakerConfig::default())
    }

    /// Get current circuit state
    pub fn state(&self) -> CircuitState {
        self.state.lock().state
    }

    /// Get metrics for monitoring
    pub fn metrics(&self) -> CircuitBreakerMetrics {
        let state = self.state.lock();
        CircuitBreakerMetrics {
            state: state.state,
            consecutive_failures: state.consecutive_failures,
            consecutive_successes: state.consecutive_successes,
            total_calls: self.total_calls.load(Ordering::Relaxed),
            total_rejections: self.total_rejections.load(Ordering::Relaxed),
            total_fallbacks: self.total_fallbacks.load(Ordering::Relaxed),
            time_in_current_state: state.last_state_change.elapsed(),
        }
    }

    /// Check if circuit allows requests and update state if needed
    fn should_allow_request(&self) -> bool {
        let mut state = self.state.lock();

        match state.state {
            CircuitState::Closed => true,
            CircuitState::Open => {
                // Check if enough time has passed to try recovery
                if state.last_state_change.elapsed() >= self.config.open_duration {
                    tracing::info!(
                        "Circuit breaker transitioning from Open to HalfOpen after {:?}",
                        self.config.open_duration
                    );
                    state.state = CircuitState::HalfOpen;
                    state.consecutive_successes = 0;
                    state.last_state_change = Instant::now();
                    self.record_state_change(CircuitState::HalfOpen);
                    true
                } else {
                    false
                }
            }
            CircuitState::HalfOpen => true,
        }
    }

    /// Record a successful operation
    fn record_success(&self) {
        let mut state = self.state.lock();
        state.consecutive_failures = 0;
        state.consecutive_successes += 1;

        if state.state == CircuitState::HalfOpen
            && state.consecutive_successes >= self.config.success_threshold
        {
            tracing::info!(
                "Circuit breaker closing after {} consecutive successes",
                state.consecutive_successes
            );
            state.state = CircuitState::Closed;
            state.last_state_change = Instant::now();
            self.record_state_change(CircuitState::Closed);
        }
    }

    /// Record a failed operation
    fn record_failure(&self) {
        let mut state = self.state.lock();
        state.consecutive_successes = 0;
        state.consecutive_failures += 1;
        state.last_failure_time = Some(Instant::now());

        match state.state {
            CircuitState::Closed => {
                if state.consecutive_failures >= self.config.failure_threshold {
                    tracing::warn!(
                        "Circuit breaker opening after {} consecutive failures",
                        state.consecutive_failures
                    );
                    state.state = CircuitState::Open;
                    state.last_state_change = Instant::now();
                    self.record_state_change(CircuitState::Open);
                }
            }
            CircuitState::HalfOpen => {
                // Single failure in half-open returns to open
                tracing::warn!("Circuit breaker returning to Open after failure in HalfOpen state");
                state.state = CircuitState::Open;
                state.last_state_change = Instant::now();
                self.record_state_change(CircuitState::Open);
            }
            CircuitState::Open => {
                // Already open, nothing to do
            }
        }
    }

    /// Record state change to metrics
    fn record_state_change(&self, new_state: CircuitState) {
        let label1 = format!("circuit_breaker_{new_state}");
        let label2 = String::from("embedding");
        crate::metrics::ERRORS_TOTAL
            .with_label_values(&[&label1, &label2])
            .inc();
    }

    /// Generate fallback embedding using simplified hash-based approach
    fn generate_fallback(&self, text: &str) -> Vec<f32> {
        self.total_fallbacks.fetch_add(1, Ordering::Relaxed);

        // Use the same hash-based approach as simplified mode
        use std::collections::hash_map::DefaultHasher;
        use std::hash::{Hash, Hasher};

        let dimension = self.inner.dimension();
        let mut embedding = vec![0.0; dimension];

        let words: Vec<&str> = text.split_whitespace().collect();

        for (i, word) in words.iter().enumerate() {
            let mut hasher = DefaultHasher::new();
            word.hash(&mut hasher);
            let hash = hasher.finish();

            for j in 0..dimension {
                let index = (i.wrapping_mul(7) + j) % dimension;
                if j < 64 {
                    embedding[index] += ((hash >> j) & 1) as f32 * 0.1;
                } else {
                    embedding[index] += ((hash >> (j % 64)) & 1) as f32 * 0.1;
                }
            }
        }

        // Normalize
        let norm: f32 = embedding.iter().map(|x| x * x).sum::<f32>().sqrt();
        if norm > 0.0 {
            for val in &mut embedding {
                *val /= norm;
            }
        }

        embedding
    }
}

impl Embedder for ResilientEmbedder {
    fn encode(&self, text: &str) -> Result<Vec<f32>> {
        self.total_calls.fetch_add(1, Ordering::Relaxed);

        if text.is_empty() {
            return Ok(vec![0.0; self.inner.dimension()]);
        }

        // Check circuit state
        if !self.should_allow_request() {
            self.total_rejections.fetch_add(1, Ordering::Relaxed);
            tracing::debug!("Circuit breaker open, using fallback embedding");
            return Ok(self.generate_fallback(text));
        }

        // Try the actual embedding
        match self.inner.encode(text) {
            Ok(embedding) => {
                self.record_success();
                Ok(embedding)
            }
            Err(e) => {
                self.record_failure();
                tracing::warn!("Embedding failed (circuit breaker tracking): {}", e);
                // Return fallback instead of error to maintain availability
                Ok(self.generate_fallback(text))
            }
        }
    }

    fn dimension(&self) -> usize {
        self.inner.dimension()
    }

    fn encode_batch(&self, texts: &[&str]) -> Result<Vec<Vec<f32>>> {
        // For batch operations, check circuit once and apply consistently
        if !self.should_allow_request() {
            self.total_rejections
                .fetch_add(texts.len() as u64, Ordering::Relaxed);
            return Ok(texts.iter().map(|t| self.generate_fallback(t)).collect());
        }

        // Process batch with individual tracking
        let mut results = Vec::with_capacity(texts.len());
        let mut any_success = false;
        let mut any_failure = false;

        for text in texts {
            self.total_calls.fetch_add(1, Ordering::Relaxed);
            match self.inner.encode(text) {
                Ok(embedding) => {
                    any_success = true;
                    results.push(embedding);
                }
                Err(_) => {
                    any_failure = true;
                    results.push(self.generate_fallback(text));
                }
            }
        }

        // Update circuit state based on batch results
        if any_failure && !any_success {
            self.record_failure();
        } else if any_success {
            self.record_success();
        }

        Ok(results)
    }
}

/// Metrics snapshot for monitoring
#[derive(Debug, Clone)]
pub struct CircuitBreakerMetrics {
    pub state: CircuitState,
    pub consecutive_failures: u32,
    pub consecutive_successes: u32,
    pub total_calls: u64,
    pub total_rejections: u64,
    pub total_fallbacks: u64,
    pub time_in_current_state: Duration,
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::path::PathBuf;

    fn create_test_embedder() -> Arc<MiniLMEmbedder> {
        let config = super::super::minilm::EmbeddingConfig {
            model_path: PathBuf::from("dummy.onnx"),
            tokenizer_path: PathBuf::from("dummy.json"),
            max_length: 256,
            use_quantized: true,
            embed_timeout_ms: 5000,
        };
        Arc::new(MiniLMEmbedder::new_simplified(config).unwrap())
    }

    #[test]
    fn test_circuit_breaker_starts_closed() {
        let embedder = create_test_embedder();
        let resilient = ResilientEmbedder::with_defaults(embedder);
        assert_eq!(resilient.state(), CircuitState::Closed);
    }

    #[test]
    fn test_circuit_breaker_metrics() {
        let embedder = create_test_embedder();
        let resilient = ResilientEmbedder::with_defaults(embedder);

        let _ = resilient.encode("test");
        let metrics = resilient.metrics();

        assert!(metrics.total_calls >= 1);
        assert_eq!(metrics.state, CircuitState::Closed);
    }

    #[test]
    fn test_fallback_generates_valid_embedding() {
        let embedder = create_test_embedder();
        let resilient = ResilientEmbedder::with_defaults(embedder);

        let fallback = resilient.generate_fallback("test input");
        assert_eq!(fallback.len(), 384);

        // Check normalization
        let norm: f32 = fallback.iter().map(|x| x * x).sum::<f32>().sqrt();
        assert!((norm - 1.0).abs() < 1e-5 || norm == 0.0);
    }
}