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
//! # Shardex - High-Performance Vector Search Engine
//!
//! Shardex provides a memory-mapped vector search engine with the ApiThing pattern
//! for consistent, composable, and type-safe operations.
//!
//! ## Architecture
//!
//! The library is built around three core concepts:
//!
//! - **[`ShardexContext`](api::ShardexContext)**: Shared state and resource management
//! - **Operations**: Types implementing [`ApiOperation`](apithing::ApiOperation) trait
//! - **Parameters**: Type-safe input objects for each operation
//!
//! ## Core Operations
//!
//! ### Index Management
//! - [`CreateIndex`](api::CreateIndex) - Create new index
//!
//! ### Document Operations
//! - [`AddPostings`](api::AddPostings) - Add vector postings
//! - [`StoreDocumentText`](api::StoreDocumentText) - Store document text
//! - [`BatchStoreDocumentText`](api::BatchStoreDocumentText) - Batch text storage
//!
//! ### Search Operations
//! - [`Search`](api::Search) - Vector similarity search
//! - [`GetDocumentText`](api::GetDocumentText) - Retrieve document text
//! - [`ExtractSnippet`](api::ExtractSnippet) - Extract text snippets
//!
//! ### Maintenance Operations
//! - [`Flush`](api::Flush) - Flush pending operations
//! - [`GetStats`](api::GetStats) - Index statistics
//! - [`GetPerformanceStats`](api::GetPerformanceStats) - Performance metrics
//!
//! ## Usage Patterns
//!
//! All operations follow the same pattern:
//!
//! ```rust
//! use apithing::ApiOperation;
//!
//! let result = OperationType::execute(&mut context, ¶meters)?;
//! ```
//!
//! ## Quick Start
//!
//! ```rust
//! use shardex::api::{
//! ShardexContext, CreateIndex, AddPostings, Search,
//! CreateIndexParams, AddPostingsParams, SearchParams
//! };
//! use shardex::{DocumentId, Posting};
//! use apithing::ApiOperation;
//!
//! # fn example() -> Result<(), Box<dyn std::error::Error>> {
//! // Create context and index
//! let mut context = ShardexContext::new();
//! let create_params = CreateIndexParams::builder()
//! .directory_path("./my_index".into())
//! .vector_size(384)
//! .shard_size(10000)
//! .batch_write_interval_ms(100)
//! .build()?;
//!
//! CreateIndex::execute(&mut context, &create_params)?;
//!
//! // Add postings
//! let postings = vec![Posting {
//! document_id: DocumentId::from_raw(1),
//! start: 0,
//! length: 100,
//! vector: vec![0.1; 384],
//! }];
//! AddPostings::execute(&mut context, &AddPostingsParams::new(postings)?)?;
//!
//! // Search
//! let results = Search::execute(&mut context, &SearchParams::builder()
//! .query_vector(vec![0.1; 384])
//! .k(10)
//! .build()?
//! )?;
//! # Ok(())
//! # }
//! ```
//!
//! ## Examples
//!
//! The `examples/` directory contains comprehensive examples:
//!
//! - `basic_usage.rs` - Basic operations
//! - `configuration.rs` - Configuration options
//! - `batch_operations.rs` - Batch processing
//! - `document_text_basic.rs` - Text storage
//! - `monitoring.rs` - Performance monitoring
//!
//! Run examples with:
//! ```bash
//! cargo run --example basic_usage
//! ```
//!
//! ## Features
//!
//! - **Consistent API**: All operations use the ApiThing pattern
//! - **Type Safety**: Parameter objects prevent errors
//! - **Shared Context**: Efficient resource management
//! - **Memory-mapped storage** for zero-copy operations and fast startup
//! - **ACID transactions** via write-ahead logging (WAL)
//! - **Incremental updates** without full index rebuilds
//! - **Document text storage** with snippet extraction
//! - **Performance monitoring** and detailed statistics
//! - **Dynamic shard management** with automatic splitting
//! - **Concurrent reads** during write operations
//! - **Bloom filter optimization** for efficient document deletion
//! - **Crash recovery** from unexpected shutdowns
//!
//! # Development Guidelines
//!
//! ## Struct Definition Standards
//!
//! ### Default Implementation Rules
//!
//! 1. **PREFER** `#[derive(Default)]` for structs with all zero/empty defaults:
//! ```rust
//! #[derive(Debug, Clone, Default)]
//! pub struct SimpleMetrics {
//! pub count: u64,
//! pub total: u64,
//! }
//! ```
//!
//! 2. **USE** manual `impl Default` only when:
//! - Non-zero defaults are needed
//! - Complex initialization is required
//! - Fields contain non-Default types
//! ```rust
//! use std::time::Instant;
//!
//! #[derive(Debug, Clone)]
//! pub struct ComplexMetrics {
//! pub start_time: Instant,
//! pub threshold: f64,
//! }
//!
//! impl Default for ComplexMetrics {
//! fn default() -> Self {
//! Self {
//! start_time: Instant::now(), // Can't derive this
//! threshold: 0.95, // Non-zero default
//! }
//! }
//! }
//! ```
//!
//! 3. **AVOID** redundant patterns like:
//! ```rust
//! // DON'T DO THIS - just derive Default instead
//! #[derive(Debug, Clone)]
//! pub struct SomeStruct {
//! pub count: u64,
//! }
//!
//! impl SomeStruct {
//! pub fn new() -> Self {
//! Self { count: 0 }
//! }
//! }
//!
//! impl Default for SomeStruct {
//! fn default() -> Self {
//! Self::new() // If new() just sets zero/empty values
//! }
//! }
//! ```
//!
//! ### Struct Size Guidelines
//!
//! 1. **MAXIMUM** 15 fields per struct (prefer 10 or fewer)
//! 2. **BREAK DOWN** large structs into logical sub-structures:
//! ```rust
//! // Instead of one large struct with 30+ fields:
//! #[derive(Debug, Clone, Default)]
//! pub struct DocumentMetrics {
//! pub documents_stored: u64,
//! pub total_size: u64,
//! pub average_latency: f64,
//! }
//! ```
//! 3. **GROUP** related fields into cohesive types
//! 4. **USE** composition over large flat structures
//!
//! ### Derive Attribute Ordering
//!
//! Always use consistent ordering for derive attributes:
//! ```rust
//! #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
//! ```
//!
//! Order: Debug, Clone, Copy (if applicable), Default, PartialEq, Eq, Hash, Serialize, Deserialize
//!
//! ### Builder Pattern Usage
//!
//! Use builder patterns for:
//! - Configuration structs with many optional parameters
//! - Complex initialization sequences
//! - Structs with validation requirements
//!
//! ```rust
//! #[derive(Debug, Clone, Default)]
//! pub struct MyConfig {
//! pub timeout: u64,
//! }
//!
//! impl MyConfig {
//! pub fn new() -> Self { Self::default() }
//!
//! pub fn with_timeout(mut self, timeout: u64) -> Self {
//! self.timeout = timeout;
//! self
//! }
//! }
//! ```
// Public API modules
// Legacy API modules (with deprecation warnings)
// Internal implementation modules (some made public for tests)
// public for tests
pub
pub
// public for tests
// public for tests
pub
pub
// public for tests
// public for tests
pub
pub
// public for tests
pub
// public for tests
pub
pub
pub
pub
// public for tests
pub
// public for tests
pub
pub
// public for tests
// public for tests
// public for tests
// public for tests
// public for tests
// public for tests
// public for tests
// Core public API - Essential types that users need
pub use ShardexError;
pub use ;
pub use ;
// Primary API - ApiThing pattern (recommended approach)
pub use ;
// Legacy API (deprecated - use api module instead)
pub use ;
pub use ShardexConfig;
// Internal re-exports for testing (not part of public API - subject to change)
pub use ;
pub use ;
pub use CowShardexIndex;
pub use CrashRecovery;
pub use DocumentTextStorage;
pub use DirectoryLayout;
pub use PerformanceMonitor as MonitoringPerformanceMonitor;
pub use PostingStorage;
pub use Shard;
pub use ShardexIndex;
pub use ;
pub use ;
pub use VectorStorage;
pub use WalSegment;
/// Type alias for Results using ShardexError
pub type Result<T> = Result;