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
//! SQLite-based graph database with unified backend support.
// Module-level dead_code suppression removed as part of CODE-02
// Individual items may still need specific allows where truly unused
//!
//! `sqlitegraph` provides a lightweight, deterministic graph database for embedded Rust applications.
//! It supports both SQLite and Native storage backends through a unified API.
//!
//! # Architecture
//!
//! The crate is organized into focused modules:
//!
//! ```text
//! sqlitegraph/
//! ├── graph/ # Core graph database (SqliteGraph, GraphEntity, GraphEdge)
//! ├── backend/ # Unified backend trait (GraphBackend, SqliteGraphBackend, NativeGraphBackend)
//! ├── algo/ # Graph algorithms (PageRank, Betweenness, Louvain, Label Propagation)
//! ├── hnsw/ # Vector similarity search (HNSW index, distance metrics)
//! ├── cache/ # LRU-K adjacency cache for traversal optimization
//! ├── introspection/ # Debugging and observability APIs
//! ├── progress/ # Progress tracking for long-running operations
//! ├── mvcc/ # MVCC-lite snapshot system
//! ├── pattern_engine/ # Triple pattern matching
//! ├── query/ # High-level query interface
//! └── recovery/ # Backup and restore utilities
//! ```
//!
//! # Features
//!
//! - **Dual Backend Support**: Choose between SQLite (feature-rich) and Native (performance-optimized) backends
//! - **Entity and Edge Storage**: Rich metadata support with JSON serialization
//! - **Pattern Matching**: Efficient triple pattern matching with cache-enabled fast-path
//! - **Traversal Algorithms**: Built-in BFS, k-hop, and shortest path algorithms
//! - **Graph Algorithms**: PageRank, Betweenness Centrality, Louvain, Label Propagation
//! - **Vector Search**: HNSW approximate nearest neighbor search with persistence
//! - **MVCC Snapshots**: Read isolation with snapshot consistency
//! - **Bulk Operations**: High-performance batch insertions for large datasets
//! - **Introspection**: Debugging APIs for cache stats, file sizes, edge counts
//! - **Progress Tracking**: Callback-based progress for long-running algorithms
//!
//! # Quick Start
//!
//! ```rust,ignore
//! use sqlitegraph::{open_graph, GraphConfig, BackendKind};
//!
//! // Use SQLite backend (default)
//! let cfg = GraphConfig::sqlite();
//! let graph = open_graph("my_graph.db", &cfg)?;
//!
//! // Or use Native backend (V3 production standard)
//! let cfg = GraphConfig::native();
//! let graph = open_graph("my_graph.db", &cfg)?;
//!
//! // Both backends support the same operations
//! let node_id = graph.insert_node(/* node spec */)?;
//! let neighbor_ids = graph.neighbors(node_id, /* query */)?;
//! ```
//!
//! # Backend Selection
//!
//! ## Feature Matrix
//!
//! | Feature | SQLite Backend | Native Backend |
//! |---------|----------------|----------------|
//! | **ACID Transactions** | ✅ Full | ✅ WAL-based |
//! | **Graph Algorithms** | ✅ Full support | ✅ Full support |
//! | **HNSW Vector Search** | ✅ With persistence | ✅ With persistence (V3 KV) |
//! | **MVCC Snapshots** | ✅ | ✅ |
//! | **Pattern Matching** | ✅ | ✅ |
//! | **Raw SQL Access** | ✅ Native | ❌ Not supported |
//! | **File Format** | SQLite DB | Custom binary (V3) |
//! | **Startup Time** | Fast | Faster |
//! | **Dependencies** | libsqlite3 | None (pure Rust) |
//! | **Write Performance** | Good | Better |
//! | **Query Performance** | Good | Better |
//!
//! ## When to Use SQLite Backend
//!
//! Choose SQLite backend when:
//! - **ACID guarantees** are critical for your application
//! - **Raw SQL access** needed for complex queries or joins
//! - **Database compatibility** with SQLite tools (sqlite3, DB Browser)
//! - **Mature ecosystem** with third-party tooling
//! - **HNSW persistence** required
//!
//! ## When to Use Native Backend
//!
//! Choose Native backend when:
//! - **Performance is critical** (faster reads/writes)
//! - **No external dependencies** desired (pure Rust)
//! - **Fast startup** with large datasets
//! - **Custom binary format (V3)** acceptable
//!
//! # Thread Safety
//!
//! ## SqliteGraph is NOT Thread-Safe
//!
//! `SqliteGraph` uses interior mutability (`RefCell`) and is **not `Sync`**:
//!
//! ```rust,ignore
//! use sqlitegraph::SqliteGraph;
//! use std::thread;
//!
//! let graph = SqliteGraph::open("test.db")?;
//!
//! // ❌ WRONG: Sharing graph across threads for writes
//! let graph_clone = graph;
//! thread::spawn(move || {
//! graph_clone.insert_node(...)?; // DATA RACE!
//! });
//!
//! // ✅ CORRECT: Use snapshots for concurrent reads
//! let snapshot = graph.snapshot()?;
//! thread::spawn(move || {
//! let neighbors = snapshot.neighbors(node_id)?; // Thread-safe
//! });
//! ```
//!
//! ## Concurrent Read Access
//!
//! Use [`GraphSnapshot`] for thread-safe concurrent reads:
//!
//! ```rust,ignore
//! use sqlitegraph::{GraphSnapshot, SqliteGraph};
//!
//! let graph = SqliteGraph::open("my_graph.db")?;
//!
//! // Create multiple snapshots for concurrent reads
//! let snapshot1 = graph.snapshot()?;
//! let snapshot2 = graph.snapshot()?;
//!
//! // Both snapshots can be used concurrently (thread-safe)
//! let handle1 = std::thread::spawn(move || {
//! snapshot1.neighbors(node_id)
//! });
//!
//! let handle2 = std::thread::spawn(move || {
//! snapshot2.neighbors(node_id)
//! });
//! ```
//!
//! ## Write Serialization
//!
//! All writes must be serialized:
//!
//! ```rust,ignore
//! // ✅ CORRECT: Single thread for all writes
//! let graph = SqliteGraph::open("my_graph.db")?;
//! for i in 0..1000 {
//! graph.insert_node(...)?;
//! graph.insert_edge(...)?;
//! }
//!
//! // ❌ WRONG: Concurrent writes
//! let graph = Arc::new(Mutex::new(graph));
//! let handle1 = thread::spawn(|| {
//! let g = graph.lock().unwrap();
//! g.insert_node(...)
//! });
//! let handle2 = thread::spawn(|| {
//! let g = graph.lock().unwrap();
//! g.insert_node(...)
//! });
//! // Even with Mutex, this can cause issues due to RefCell
//! ```
//!
//! # Error Handling
//!
//! All operations return [`Result<T, SqliteGraphError>`]:
//!
//! ```rust,ignore
//! use sqlitegraph::{SqliteGraph, SqliteGraphError};
//!
//! let graph = SqliteGraph::open("my_graph.db")?;
//!
//! match graph.insert_node(node_spec) {
//! Ok(node_id) => println!("Created node {}", node_id),
//! Err(SqliteGraphError::EntityNotFound) => {
//! println!("Node not found");
//! }
//! Err(SqliteGraphError::DatabaseError(e)) => {
//! eprintln!("Database error: {}", e);
//! }
//! Err(e) => {
//! eprintln!("Other error: {}", e);
//! }
//! }
//! ```
//!
//! # Performance Comparison
//!
//! ## Read Performance
//! - **SQLite Backend**: 10-100μs per neighbor lookup (cached: ~100ns)
//! - **Native Backend**: 1-10μs per neighbor lookup (cached: ~100ns)
//! - **Cache hit ratio**: 80-95% for traversal workloads
//!
//! ## Write Performance
//! - **SQLite Backend**: 100-500μs per insert (transaction-batched)
//! - **Native Backend**: 10-100μs per insert (transaction-batched)
//! - **Bulk insert**: 10-100x faster with `bulk_insert_entities()`
//!
//! ## Memory Usage
//! - **Base overhead**: O(V + E) for graph storage
//! - **Cache overhead**: 10-20% additional memory
//! - **HNSW index**: 2-3x vector data size
//!
//! # Public API Organization
//!
//! This crate exports a clean, stable public API organized as follows:
//!
//! ## Core Types
//! - [`GraphEntity`] - Graph node/vertex representation
//! - [`GraphEdge`] - Graph edge/relationship representation
//! - [`GraphBackend`] - Unified trait for backend implementations
//! - [`SqliteGraphBackend`] - SQLite backend implementation
//! - [`V3Backend`] - Native V3 backend implementation
//!
//! ## Configuration
//! - [`BackendKind`] - Runtime backend selection enum
//! - [`GraphConfig`] - Unified configuration for both backends
//! - [`SqliteConfig`] - SQLite-specific options
//! - [`NativeConfig`] - Native-specific options
//! - [`open_graph()`] - Unified factory function
//!
//! ## Operations
//! - [`insert_node()`], [`insert_edge()`] - Single entity/edge insertion
//! - [`bulk_insert_entities()`], [`bulk_insert_edges()`] - Batch operations
//! - [`neighbors()`] - Direct neighbor queries
//! - [`bfs()`], [`k_hop()`], [`shortest_path()`] - Graph traversal algorithms
//! - [`pattern_engine`] - Pattern matching and triple storage
//!
//! ## Graph Algorithms
//! - [`pagerank`] - PageRank centrality
//! - [`betweenness_centrality`] - Betweenness centrality
//! - [`louvain_communities`] - Louvain community detection
//! - [`label_propagation`] - Label propagation algorithm
//!
//! ## Vector Search
//! - [`hnsw::HnswIndex`] - HNSW vector search index
//! - [`hnsw::HnswConfig`] - HNSW configuration
//! - [`hnsw::DistanceMetric`] - Distance metrics (Cosine, Euclidean, etc.)
//!
//! ## Utilities
//! - [`SqliteGraphError`] - Comprehensive error handling
//! - [`GraphSnapshot`] - MVCC snapshot system
//! - [`GraphIntrospection`] - Introspection and debugging APIs
//! - [`ProgressCallback`] - Algorithm progress tracking
//! - [`recovery`] - Database backup and restore utilities
// Core public modules
// Re-export core utilities that are stable public APIs
pub use ;
pub use ;
pub use ;
pub use ;
pub use ;
pub use match_triples_fast;
pub use GraphQuery;
pub use ;
pub use SnapshotId;
// Re-export backend implementations
pub use V3Backend as NativeGraphBackend;
pub use ;
pub use ;
// Re-export configuration and factory
pub use ;
// Re-export error types
pub use SqliteGraphError;
// Re-export graph core types
pub use ;
// Re-export graph algorithms
pub use ;
// Re-export progress tracking
pub use ;
// Re-export introspection API
pub use ;
// Internal modules - not part of public API
// Public for tests
// Public for tests
// Public for tests
// Public for binary
// Public for tests
// Public for tests
// Public for tests
// Public for tests
// Already moved to core above
// Public for tests and progress API usage
// Public for internal use and tests
// Public for binary
// Public for tests // Public for tests
// Core public modules (these were accidentally removed)
// Already exported above
// Already exported above
// Already exported above
// Already exported above
// Modules that need to remain public for specific use cases
// Public for tests
// Public for tests
// Public for tests
// Public for tests
// Public for examples
// Sparse inference engine
// Public for binary // HNSW vector search capabilities
// Dependency monitoring module (feature-gated)
// Re-export cache statistics for benchmarking
pub use CacheStats;