pulsehive-db 0.5.0

Embedded database for agentic AI systems — collective memory for multi-agent coordination
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
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
//! Error types for PulseDB.
//!
//! PulseDB uses a hierarchical error system:
//! - `PulseDBError` is the top-level error returned by all public APIs
//! - Specific error types (`StorageError`, `ValidationError`) provide detail
//!
//! # Error Handling Pattern
//! ```rust
//! use pulsedb::{PulseDB, Config, Result};
//!
//! fn example() -> Result<()> {
//!     let dir = tempfile::tempdir().unwrap();
//!     let db = PulseDB::open(dir.path().join("test.db"), Config::default())?;
//!     // ... operations that may fail ...
//!     db.close()?;
//!     Ok(())
//! }
//! ```

use std::path::PathBuf;
use thiserror::Error;

#[cfg(feature = "sync")]
use crate::sync::SyncError;

/// Result type alias for PulseDB operations.
pub type Result<T> = std::result::Result<T, PulseDBError>;

/// Top-level error enum for all PulseDB operations.
///
/// This is the only error type returned by public APIs.
/// Use pattern matching to handle specific error cases.
#[derive(Debug, Error)]
pub enum PulseDBError {
    /// Storage layer error (I/O, corruption, transactions).
    #[error("Storage error: {0}")]
    Storage(#[from] StorageError),

    /// Input validation error.
    #[error("Validation error: {0}")]
    Validation(#[from] ValidationError),

    /// Configuration error.
    #[error("Configuration error: {reason}")]
    Config {
        /// Description of what's wrong with the configuration.
        reason: String,
    },

    /// Requested entity not found.
    #[error("{0}")]
    NotFound(#[from] NotFoundError),

    /// General I/O error.
    #[error("I/O error: {0}")]
    Io(#[from] std::io::Error),

    /// Embedding generation/validation error.
    #[error("Embedding error: {0}")]
    Embedding(String),

    /// Vector index error (HNSW operations).
    #[error("Vector index error: {0}")]
    Vector(String),

    /// Watch system error (subscription or event delivery).
    #[error("Watch error: {0}")]
    Watch(String),

    /// Internal error (e.g., async runtime failure, task join error).
    #[error("Internal error: {0}")]
    Internal(String),

    /// Database is in read-only mode.
    ///
    /// Returned when a mutation method is called on a database opened
    /// with `Config::read_only()`.
    #[error("Database is in read-only mode")]
    ReadOnly,

    /// Sync protocol error.
    ///
    /// Only available when the `sync` feature is enabled.
    #[cfg(feature = "sync")]
    #[cfg_attr(docsrs, doc(cfg(feature = "sync")))]
    #[error("Sync error: {0}")]
    Sync(#[from] SyncError),
}

impl PulseDBError {
    /// Creates a configuration error with the given reason.
    pub fn config(reason: impl Into<String>) -> Self {
        Self::Config {
            reason: reason.into(),
        }
    }

    /// Creates an embedding error with the given message.
    pub fn embedding(msg: impl Into<String>) -> Self {
        Self::Embedding(msg.into())
    }

    /// Creates a vector index error with the given message.
    pub fn vector(msg: impl Into<String>) -> Self {
        Self::Vector(msg.into())
    }

    /// Creates a watch system error with the given message.
    pub fn watch(msg: impl Into<String>) -> Self {
        Self::Watch(msg.into())
    }

    /// Creates an internal error with the given message.
    pub fn internal(msg: impl Into<String>) -> Self {
        Self::Internal(msg.into())
    }

    /// Returns true if this is a "not found" error.
    pub fn is_not_found(&self) -> bool {
        matches!(self, Self::NotFound(_))
    }

    /// Returns true if this is a validation error.
    pub fn is_validation(&self) -> bool {
        matches!(self, Self::Validation(_))
    }

    /// Returns true if this is a storage error.
    pub fn is_storage(&self) -> bool {
        matches!(self, Self::Storage(_))
    }

    /// Returns true if this is a vector index error.
    pub fn is_vector(&self) -> bool {
        matches!(self, Self::Vector(_))
    }

    /// Returns true if this is a watch system error.
    pub fn is_watch(&self) -> bool {
        matches!(self, Self::Watch(_))
    }

    /// Returns true if this is an embedding error.
    pub fn is_embedding(&self) -> bool {
        matches!(self, Self::Embedding(_))
    }

    /// Returns true if this is an internal error.
    pub fn is_internal(&self) -> bool {
        matches!(self, Self::Internal(_))
    }

    /// Returns true if this is a configuration error.
    pub fn is_config(&self) -> bool {
        matches!(self, Self::Config { .. })
    }

    /// Returns true if this is an I/O error.
    pub fn is_io(&self) -> bool {
        matches!(self, Self::Io(_))
    }

    /// Returns true if this is a read-only error.
    pub fn is_read_only(&self) -> bool {
        matches!(self, Self::ReadOnly)
    }

    /// Returns true if this is a sync error.
    ///
    /// Only available when the `sync` feature is enabled.
    #[cfg(feature = "sync")]
    #[cfg_attr(docsrs, doc(cfg(feature = "sync")))]
    pub fn is_sync(&self) -> bool {
        matches!(self, Self::Sync(_))
    }
}

/// Storage-related errors.
///
/// These errors indicate problems with the underlying storage layer.
#[derive(Debug, Error)]
pub enum StorageError {
    /// Database file or data is corrupted.
    #[error("Database corrupted: {0}")]
    Corrupted(String),

    /// Database file not found at expected path.
    #[error("Database not found: {0}")]
    DatabaseNotFound(PathBuf),

    /// Database is locked by another process.
    #[error("Database is locked by another writer")]
    DatabaseLocked,

    /// Transaction failed (commit, rollback, etc.).
    #[error("Transaction failed: {0}")]
    Transaction(String),

    /// Serialization/deserialization error.
    #[error("Serialization error: {0}")]
    Serialization(String),

    /// Error from the redb storage engine.
    #[error("Storage engine error: {0}")]
    Redb(String),

    /// Database schema version doesn't match expected version.
    #[error("Schema version mismatch: expected {expected}, found {found}")]
    SchemaVersionMismatch {
        /// Expected schema version.
        expected: u32,
        /// Actual schema version found in database.
        found: u32,
    },

    /// Table not found in database.
    #[error("Table not found: {0}")]
    TableNotFound(String),
}

impl StorageError {
    /// Creates a corruption error with the given message.
    pub fn corrupted(msg: impl Into<String>) -> Self {
        Self::Corrupted(msg.into())
    }

    /// Creates a transaction error with the given message.
    pub fn transaction(msg: impl Into<String>) -> Self {
        Self::Transaction(msg.into())
    }

    /// Creates a serialization error with the given message.
    pub fn serialization(msg: impl Into<String>) -> Self {
        Self::Serialization(msg.into())
    }

    /// Creates a redb error with the given message.
    pub fn redb(msg: impl Into<String>) -> Self {
        Self::Redb(msg.into())
    }
}

// Conversions from redb error types
impl From<redb::Error> for StorageError {
    fn from(err: redb::Error) -> Self {
        StorageError::Redb(err.to_string())
    }
}

impl From<redb::DatabaseError> for StorageError {
    fn from(err: redb::DatabaseError) -> Self {
        StorageError::Redb(err.to_string())
    }
}

impl From<redb::TransactionError> for StorageError {
    fn from(err: redb::TransactionError) -> Self {
        StorageError::Transaction(err.to_string())
    }
}

impl From<redb::CommitError> for StorageError {
    fn from(err: redb::CommitError) -> Self {
        StorageError::Transaction(format!("Commit failed: {}", err))
    }
}

impl From<redb::TableError> for StorageError {
    fn from(err: redb::TableError) -> Self {
        StorageError::Redb(format!("Table error: {}", err))
    }
}

impl From<redb::StorageError> for StorageError {
    fn from(err: redb::StorageError) -> Self {
        StorageError::Redb(format!("Storage error: {}", err))
    }
}

// Convert bincode errors to StorageError
impl From<bincode::Error> for StorageError {
    fn from(err: bincode::Error) -> Self {
        StorageError::Serialization(err.to_string())
    }
}

// Also allow direct conversion to PulseDBError for convenience
impl From<redb::Error> for PulseDBError {
    fn from(err: redb::Error) -> Self {
        PulseDBError::Storage(StorageError::from(err))
    }
}

impl From<redb::DatabaseError> for PulseDBError {
    fn from(err: redb::DatabaseError) -> Self {
        PulseDBError::Storage(StorageError::from(err))
    }
}

impl From<redb::TransactionError> for PulseDBError {
    fn from(err: redb::TransactionError) -> Self {
        PulseDBError::Storage(StorageError::from(err))
    }
}

impl From<redb::CommitError> for PulseDBError {
    fn from(err: redb::CommitError) -> Self {
        PulseDBError::Storage(StorageError::from(err))
    }
}

impl From<redb::TableError> for PulseDBError {
    fn from(err: redb::TableError) -> Self {
        PulseDBError::Storage(StorageError::from(err))
    }
}

impl From<redb::StorageError> for PulseDBError {
    fn from(err: redb::StorageError) -> Self {
        PulseDBError::Storage(StorageError::from(err))
    }
}

impl From<bincode::Error> for PulseDBError {
    fn from(err: bincode::Error) -> Self {
        PulseDBError::Storage(StorageError::from(err))
    }
}

/// Validation errors for input data.
///
/// These errors indicate problems with data provided by the caller.
#[derive(Debug, Error)]
pub enum ValidationError {
    /// Embedding dimension doesn't match collective's configured dimension.
    #[error("Embedding dimension mismatch: expected {expected}, got {got}")]
    DimensionMismatch {
        /// Expected dimension from collective configuration.
        expected: usize,
        /// Actual dimension provided.
        got: usize,
    },

    /// A field has an invalid value.
    #[error("Invalid field '{field}': {reason}")]
    InvalidField {
        /// Name of the invalid field.
        field: String,
        /// Why the value is invalid.
        reason: String,
    },

    /// Content exceeds maximum allowed size.
    #[error("Content too large: {size} bytes (max: {max} bytes)")]
    ContentTooLarge {
        /// Actual content size in bytes.
        size: usize,
        /// Maximum allowed size in bytes.
        max: usize,
    },

    /// A required field is missing or empty.
    #[error("Required field missing: {field}")]
    RequiredField {
        /// Name of the missing field.
        field: String,
    },

    /// Too many items in a collection field.
    #[error("Too many items in '{field}': {count} (max: {max})")]
    TooManyItems {
        /// Name of the field.
        field: String,
        /// Actual count.
        count: usize,
        /// Maximum allowed.
        max: usize,
    },
}

impl ValidationError {
    /// Creates a dimension mismatch error.
    pub fn dimension_mismatch(expected: usize, got: usize) -> Self {
        Self::DimensionMismatch { expected, got }
    }

    /// Creates an invalid field error.
    pub fn invalid_field(field: impl Into<String>, reason: impl Into<String>) -> Self {
        Self::InvalidField {
            field: field.into(),
            reason: reason.into(),
        }
    }

    /// Creates a content too large error.
    pub fn content_too_large(size: usize, max: usize) -> Self {
        Self::ContentTooLarge { size, max }
    }

    /// Creates a required field error.
    pub fn required_field(field: impl Into<String>) -> Self {
        Self::RequiredField {
            field: field.into(),
        }
    }

    /// Creates a too many items error.
    pub fn too_many_items(field: impl Into<String>, count: usize, max: usize) -> Self {
        Self::TooManyItems {
            field: field.into(),
            count,
            max,
        }
    }
}

/// Not found errors for specific entity types.
#[derive(Debug, Error)]
pub enum NotFoundError {
    /// Collective with given ID not found.
    #[error("Collective not found: {0}")]
    Collective(String),

    /// Experience with given ID not found.
    #[error("Experience not found: {0}")]
    Experience(String),

    /// Relation with given ID not found.
    #[error("Relation not found: {0}")]
    Relation(String),

    /// Insight with given ID not found.
    #[error("Insight not found: {0}")]
    Insight(String),

    /// Activity not found for given agent/collective pair.
    #[error("Activity not found: {0}")]
    Activity(String),
}

impl NotFoundError {
    /// Creates a collective not found error.
    pub fn collective(id: impl ToString) -> Self {
        Self::Collective(id.to_string())
    }

    /// Creates an experience not found error.
    pub fn experience(id: impl ToString) -> Self {
        Self::Experience(id.to_string())
    }

    /// Creates a relation not found error.
    pub fn relation(id: impl ToString) -> Self {
        Self::Relation(id.to_string())
    }

    /// Creates an insight not found error.
    pub fn insight(id: impl ToString) -> Self {
        Self::Insight(id.to_string())
    }

    /// Creates an activity not found error.
    pub fn activity(id: impl ToString) -> Self {
        Self::Activity(id.to_string())
    }
}

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

    #[test]
    fn test_error_display() {
        let err = PulseDBError::config("Invalid dimension");
        assert_eq!(err.to_string(), "Configuration error: Invalid dimension");
    }

    #[test]
    fn test_storage_error_display() {
        let err = StorageError::SchemaVersionMismatch {
            expected: 2,
            found: 1,
        };
        assert_eq!(
            err.to_string(),
            "Schema version mismatch: expected 2, found 1"
        );
    }

    #[test]
    fn test_validation_error_display() {
        let err = ValidationError::dimension_mismatch(384, 768);
        assert_eq!(
            err.to_string(),
            "Embedding dimension mismatch: expected 384, got 768"
        );
    }

    #[test]
    fn test_not_found_error_display() {
        let err = NotFoundError::collective("abc-123");
        assert_eq!(err.to_string(), "Collective not found: abc-123");
    }

    #[test]
    fn test_is_not_found() {
        let err: PulseDBError = NotFoundError::collective("test").into();
        assert!(err.is_not_found());
        assert!(!err.is_validation());
    }

    #[test]
    fn test_is_validation() {
        let err: PulseDBError = ValidationError::required_field("content").into();
        assert!(err.is_validation());
        assert!(!err.is_not_found());
    }

    #[test]
    fn test_vector_error_display() {
        let err = PulseDBError::vector("HNSW insert failed");
        assert_eq!(err.to_string(), "Vector index error: HNSW insert failed");
        assert!(err.is_vector());
        assert!(!err.is_storage());
    }

    #[test]
    fn test_error_conversion_chain() {
        // Simulate a storage error propagating up
        fn inner() -> Result<()> {
            Err(StorageError::corrupted("test corruption"))?
        }

        let result = inner();
        assert!(result.is_err());
        assert!(result.unwrap_err().is_storage());
    }

    #[test]
    fn test_watch_error_display() {
        let err = PulseDBError::watch("subscribers lock poisoned");
        assert_eq!(err.to_string(), "Watch error: subscribers lock poisoned");
    }

    #[test]
    fn test_watch_constructor() {
        let err = PulseDBError::watch("test");
        assert!(err.is_watch());
        assert!(!err.is_storage());
    }

    #[test]
    fn test_is_watch() {
        let err = PulseDBError::watch("test");
        assert!(err.is_watch());
        assert!(!err.is_not_found());
    }

    #[test]
    fn test_is_embedding() {
        let err = PulseDBError::embedding("model load failed");
        assert!(err.is_embedding());
        assert!(!err.is_vector());
    }

    #[test]
    fn test_is_internal() {
        let err = PulseDBError::internal("task join failed");
        assert!(err.is_internal());
        assert!(!err.is_storage());
    }

    #[test]
    fn test_is_config() {
        let err = PulseDBError::config("invalid dimension");
        assert!(err.is_config());
        assert!(!err.is_validation());
    }

    #[test]
    fn test_is_io() {
        let err = PulseDBError::Io(std::io::Error::new(
            std::io::ErrorKind::NotFound,
            "file missing",
        ));
        assert!(err.is_io());
        assert!(!err.is_storage());
    }
}