shardex 0.1.0

A high-performance memory-mapped vector search engine with ACID transactions and incremental updates
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
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
//! Configuration structures for Shardex
//!
//! This module provides the configuration system for Shardex, including
//! parameter validation and builder pattern implementation.

use crate::deduplication::DeduplicationPolicy;
use crate::error::ShardexError;
use serde::{Deserialize, Serialize};
use std::path::PathBuf;

/// Configuration for slop factor behavior
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SlopFactorConfig {
    /// Default slop factor for search operations
    pub default_factor: usize,
    /// Minimum allowed slop factor
    pub min_factor: usize,
    /// Maximum allowed slop factor
    pub max_factor: usize,
    /// Enable adaptive slop factor selection
    pub adaptive_enabled: bool,
    /// Performance threshold in milliseconds for adaptive adjustment
    pub performance_threshold_ms: u64,
}

impl Default for SlopFactorConfig {
    fn default() -> Self {
        Self {
            default_factor: 3,
            min_factor: 1,
            max_factor: 100,
            adaptive_enabled: false,
            performance_threshold_ms: 100,
        }
    }
}

impl SlopFactorConfig {
    /// Create a new slop factor configuration with default values
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the default slop factor
    pub fn default_factor(mut self, factor: usize) -> Self {
        self.default_factor = factor;
        self
    }

    /// Set the minimum slop factor
    pub fn min_factor(mut self, factor: usize) -> Self {
        self.min_factor = factor;
        self
    }

    /// Set the maximum slop factor
    pub fn max_factor(mut self, factor: usize) -> Self {
        self.max_factor = factor;
        self
    }

    /// Enable or disable adaptive slop factor selection
    pub fn adaptive_enabled(mut self, enabled: bool) -> Self {
        self.adaptive_enabled = enabled;
        self
    }

    /// Set the performance threshold for adaptive adjustment
    pub fn performance_threshold_ms(mut self, threshold_ms: u64) -> Self {
        self.performance_threshold_ms = threshold_ms;
        self
    }

    /// Validate the slop factor configuration
    pub fn validate(&self) -> Result<(), ShardexError> {
        if self.default_factor == 0 {
            return Err(ShardexError::config_error(
                "slop_factor_config.default_factor",
                "must be greater than 0",
                "Set default_factor to a positive integer (recommended: 3-10 for most use cases)",
            ));
        }

        if self.min_factor == 0 {
            return Err(ShardexError::config_error(
                "slop_factor_config.min_factor",
                "must be greater than 0",
                "Set min_factor to at least 1 (minimum valid slop factor)",
            ));
        }

        if self.max_factor == 0 {
            return Err(ShardexError::config_error(
                "slop_factor_config.max_factor",
                "must be greater than 0",
                "Set max_factor to a reasonable upper bound (recommended: 100 or less to avoid performance issues)",
            ));
        }

        if self.min_factor > self.max_factor {
            return Err(ShardexError::config_error(
                "slop_factor_config",
                format!(
                    "min_factor ({}) cannot be greater than max_factor ({})",
                    self.min_factor, self.max_factor
                ),
                "Ensure min_factor <= max_factor. For example: min_factor=1, max_factor=10",
            ));
        }

        if self.default_factor < self.min_factor || self.default_factor > self.max_factor {
            return Err(ShardexError::config_error(
                "slop_factor_config.default_factor",
                format!(
                    "value {} is outside the allowed range [{}, {}]",
                    self.default_factor, self.min_factor, self.max_factor
                ),
                format!(
                    "Set default_factor to a value between {} and {}",
                    self.min_factor, self.max_factor
                ),
            ));
        }

        if self.performance_threshold_ms == 0 {
            return Err(ShardexError::config_error(
                "slop_factor_config.performance_threshold_ms",
                "must be greater than 0",
                "Set performance_threshold_ms to a positive value in milliseconds (recommended: 50-200ms)",
            ));
        }

        Ok(())
    }

    /// Build the configuration after validation
    pub fn build(self) -> Result<Self, ShardexError> {
        self.validate()?;
        Ok(self)
    }

    /// Calculate optimal slop factor based on index characteristics
    pub fn calculate_optimal_slop(&self, vector_size: usize, shard_count: usize) -> usize {
        if !self.adaptive_enabled {
            return self.default_factor;
        }

        // Adaptive algorithm based on index characteristics
        // Larger vector sizes benefit from more shards to search
        // More shards available allows for higher selectivity
        let size_factor = ((vector_size as f64).log2() / 10.0).max(0.1) as usize;
        let shard_factor = (shard_count as f64 / 10.0).sqrt().max(1.0) as usize;

        let calculated = self.default_factor + size_factor + shard_factor;
        calculated.clamp(self.min_factor, self.max_factor)
    }
}

/// Configuration for a Shardex index
///
/// # Example
///
/// ```rust
/// use shardex::ShardexConfig;
///
/// // Create default configuration
/// let config = ShardexConfig::new()
///     .directory_path("./my_index")
///     .vector_size(768)
///     .shard_size(50000)
///     .batch_write_interval_ms(50);
///
/// assert_eq!(config.vector_size, 768);
/// assert_eq!(config.shard_size, 50000);
/// ```
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ShardexConfig {
    /// Directory path where the index will be stored
    pub directory_path: PathBuf,
    /// Size of embedding vectors in dimensions
    pub vector_size: usize,
    /// Maximum number of entries per shard
    pub shard_size: usize,
    /// Maximum number of entries per Shardex segment
    pub shardex_segment_size: usize,
    /// Size of each WAL segment in bytes
    pub wal_segment_size: usize,
    /// Safety margin as percentage of WAL segment size (0.0 to 1.0, default 0.5 = 50%)
    pub wal_safety_margin: f32,
    /// Interval between batch writes in milliseconds
    pub batch_write_interval_ms: u64,
    /// Slop factor configuration for search operations
    pub slop_factor_config: SlopFactorConfig,
    /// Size of bloom filters in bits
    pub bloom_filter_size: usize,
    /// Deduplication policy for search results
    pub deduplication_policy: DeduplicationPolicy,
    /// Maximum size of individual document text in bytes
    ///
    /// This configuration parameter sets the maximum allowed size for document text
    /// storage to prevent memory exhaustion and ensure reasonable performance.
    ///
    /// # Limits
    ///
    /// - **Minimum**: 1024 bytes (1KB) - prevents unreasonably small documents
    /// - **Maximum**: 1073741824 bytes (1GB) - prevents memory exhaustion
    /// - **Default**: 10485760 bytes (10MB) - suitable for most use cases
    ///
    /// # Performance Implications
    ///
    /// - **Memory Usage**: Each document text is loaded into memory during extraction
    /// - **Storage**: Larger limits increase disk space requirements
    /// - **I/O Performance**: Very large documents may impact read/write performance
    ///
    /// # Use Case Guidelines
    ///
    /// - **Small Documents** (1MB-5MB): Code snippets, articles, short documents
    /// - **Medium Documents** (10MB-50MB): Research papers, manuals, technical documentation
    /// - **Large Documents** (50MB-1GB): Books, large technical specifications, data files
    ///
    /// # Example
    ///
    /// ```rust
    /// use shardex::ShardexConfig;
    ///
    /// // Conservative configuration for memory-constrained environments
    /// let config = ShardexConfig::new()
    ///     .max_document_text_size(1024 * 1024); // 1MB per document
    ///
    /// // High-capacity configuration for large documents
    /// let config = ShardexConfig::new()
    ///     .max_document_text_size(100 * 1024 * 1024); // 100MB per document
    /// ```
    pub max_document_text_size: usize,
}

impl Default for ShardexConfig {
    fn default() -> Self {
        Self {
            directory_path: PathBuf::from("./shardex_index"),
            vector_size: 384,
            shard_size: 10000,
            shardex_segment_size: 1000,
            wal_segment_size: 1024 * 1024, // 1MB
            wal_safety_margin: 0.5,        // 50% safety margin
            batch_write_interval_ms: 100,
            slop_factor_config: SlopFactorConfig::default(),
            bloom_filter_size: 1024,
            deduplication_policy: DeduplicationPolicy::default(),
            max_document_text_size: 10 * 1024 * 1024, // 10MB
        }
    }
}

impl ShardexConfig {
    /// Create a new configuration with default values
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the directory path for the index
    pub fn directory_path<P: Into<PathBuf>>(mut self, path: P) -> Self {
        self.directory_path = path.into();
        self
    }

    /// Set the vector size (dimensions)
    pub fn vector_size(mut self, size: usize) -> Self {
        self.vector_size = size;
        self
    }

    /// Set the maximum entries per shard
    pub fn shard_size(mut self, size: usize) -> Self {
        self.shard_size = size;
        self
    }

    /// Set the maximum entries per Shardex segment
    pub fn shardex_segment_size(mut self, size: usize) -> Self {
        self.shardex_segment_size = size;
        self
    }

    /// Set the WAL segment size in bytes
    pub fn wal_segment_size(mut self, size: usize) -> Self {
        self.wal_segment_size = size;
        self
    }

    /// Set the WAL safety margin as a percentage (0.0 to 1.0)
    /// Default is 0.5 (50%). Higher values provide more safety but reduce batch capacity.
    pub fn wal_safety_margin(mut self, margin: f32) -> Self {
        self.wal_safety_margin = margin.clamp(0.0, 1.0);
        self
    }

    /// Set the batch write interval in milliseconds
    pub fn batch_write_interval_ms(mut self, ms: u64) -> Self {
        self.batch_write_interval_ms = ms;
        self
    }

    /// Set the default slop factor (deprecated - use slop_factor_config)
    pub fn default_slop_factor(mut self, factor: usize) -> Self {
        self.slop_factor_config.default_factor = factor;
        self
    }

    /// Set the slop factor configuration
    pub fn slop_factor_config(mut self, config: SlopFactorConfig) -> Self {
        self.slop_factor_config = config;
        self
    }

    /// Set the bloom filter size in bits
    pub fn bloom_filter_size(mut self, size: usize) -> Self {
        self.bloom_filter_size = size;
        self
    }

    /// Set the deduplication policy for search results
    pub fn deduplication_policy(mut self, policy: DeduplicationPolicy) -> Self {
        self.deduplication_policy = policy;
        self
    }

    /// Set the maximum document text size in bytes
    ///
    /// This parameter controls the maximum size of individual document text that can be
    /// stored in the index. The size must be between 1KB (1024 bytes) and 1GB (1073741824 bytes).
    ///
    /// # Arguments
    ///
    /// - `size` - Maximum document text size in bytes
    ///
    /// # Validation
    ///
    /// The provided size will be validated when `build()` or `validate()` is called:
    /// - Must be at least 1024 bytes (1KB)
    /// - Must not exceed 1073741824 bytes (1GB)
    ///
    /// # Example
    ///
    /// ```rust
    /// use shardex::ShardexConfig;
    ///
    /// let config = ShardexConfig::new()
    ///     .max_document_text_size(50 * 1024 * 1024) // 50MB
    ///     .build()
    ///     .expect("Valid configuration");
    /// ```
    pub fn max_document_text_size(mut self, size: usize) -> Self {
        self.max_document_text_size = size;
        self
    }

    /// Validate the configuration parameters
    pub fn validate(&self) -> Result<(), ShardexError> {
        if self.vector_size == 0 {
            return Err(ShardexError::config_error(
                "vector_size",
                "must be greater than 0",
                "Set vector_size to match your embedding model dimensions (e.g., 384 for sentence transformers, 1536 for OpenAI embeddings)",
            ));
        }

        if self.vector_size > 10000 {
            return Err(ShardexError::config_error(
                "vector_size",
                format!(
                    "value {} is unusually large and may cause performance issues",
                    self.vector_size
                ),
                "Most embedding models use 384-1536 dimensions. Verify this matches your model's output size.",
            ));
        }

        if self.shard_size == 0 {
            return Err(ShardexError::config_error(
                "shard_size",
                "must be greater than 0",
                "Set shard_size to control how many vectors per shard (recommended: 10000-100000 depending on memory constraints)",
            ));
        }

        if self.shard_size > 1_000_000 {
            return Err(ShardexError::config_error(
                "shard_size",
                format!("value {} may cause excessive memory usage", self.shard_size),
                "Consider reducing shard_size to 100000 or less to avoid memory issues",
            ));
        }

        if self.shardex_segment_size == 0 {
            return Err(ShardexError::config_error(
                "shardex_segment_size",
                "must be greater than 0",
                "Set shardex_segment_size to control file segment sizes (recommended: 64MB-1GB)",
            ));
        }

        if self.wal_segment_size < 1024 {
            return Err(ShardexError::config_error(
                "wal_segment_size",
                format!(
                    "value {} bytes is too small for efficient WAL operations",
                    self.wal_segment_size
                ),
                "Set wal_segment_size to at least 1024 bytes (recommended: 1MB-64MB)",
            ));
        }

        if self.wal_segment_size > 1024 * 1024 * 1024 {
            return Err(ShardexError::config_error(
                "wal_segment_size",
                format!("value {} bytes exceeds 1GB limit", self.wal_segment_size),
                "Set wal_segment_size to 1GB or less to avoid memory and disk space issues",
            ));
        }

        if self.wal_safety_margin < 0.0 || self.wal_safety_margin > 1.0 {
            return Err(ShardexError::config_error(
                "wal_safety_margin",
                format!("value {} must be between 0.0 and 1.0", self.wal_safety_margin),
                "Set wal_safety_margin between 0.0 (no safety margin) and 1.0 (100% margin). Recommended: 0.5 (50%)",
            ));
        }

        if self.batch_write_interval_ms == 0 {
            return Err(ShardexError::config_error(
                "batch_write_interval_ms",
                "must be greater than 0",
                "Set batch_write_interval_ms to control how often batches are flushed (recommended: 100-1000ms)",
            ));
        }

        if self.batch_write_interval_ms > 30000 {
            return Err(ShardexError::config_error(
                "batch_write_interval_ms",
                format!(
                    "value {} ms is too large and may cause data loss on crashes",
                    self.batch_write_interval_ms
                ),
                "Set batch_write_interval_ms to 30 seconds or less to limit potential data loss",
            ));
        }

        // Validate slop factor configuration
        self.slop_factor_config.validate()?;

        if self.bloom_filter_size == 0 {
            return Err(ShardexError::config_error(
                "bloom_filter_size",
                "must be greater than 0",
                "Set bloom_filter_size in bits (recommended: 1000000 for ~100k vectors with 1% false positive rate)",
            ));
        }

        // Validate document text size limits
        const MIN_DOCUMENT_SIZE: usize = 1024; // 1KB minimum
        const MAX_DOCUMENT_SIZE: usize = 1024 * 1024 * 1024; // 1GB maximum

        // Allow 0 to disable text storage, otherwise enforce minimum
        if self.max_document_text_size > 0 && self.max_document_text_size < MIN_DOCUMENT_SIZE {
            return Err(ShardexError::config_error(
                "max_document_text_size",
                format!(
                    "Size {} bytes is below minimum {}",
                    self.max_document_text_size, MIN_DOCUMENT_SIZE
                ),
                format!(
                    "Set max_document_text_size to 0 to disable text storage or at least {} bytes to enable",
                    MIN_DOCUMENT_SIZE
                ),
            ));
        }

        if self.max_document_text_size > MAX_DOCUMENT_SIZE {
            return Err(ShardexError::config_error(
                "max_document_text_size",
                format!(
                    "Size {} bytes exceeds maximum {}",
                    self.max_document_text_size, MAX_DOCUMENT_SIZE
                ),
                format!("Set max_document_text_size to at most {} bytes", MAX_DOCUMENT_SIZE),
            ));
        }

        // Validate directory path is not empty
        if self.directory_path.as_os_str().is_empty() {
            return Err(ShardexError::Config("Directory path cannot be empty".to_string()));
        }

        Ok(())
    }

    /// Build the configuration after validation
    pub fn build(self) -> Result<Self, ShardexError> {
        self.validate()?;
        Ok(self)
    }
}

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

    #[test]
    fn test_default_config() {
        let config = ShardexConfig::default();
        assert_eq!(config.directory_path, PathBuf::from("./shardex_index"));
        assert_eq!(config.vector_size, 384);
        assert_eq!(config.shard_size, 10000);
        assert_eq!(config.shardex_segment_size, 1000);
        assert_eq!(config.wal_segment_size, 1024 * 1024);
        assert_eq!(config.batch_write_interval_ms, 100);
        assert_eq!(config.slop_factor_config.default_factor, 3);
        assert_eq!(config.bloom_filter_size, 1024);
        assert_eq!(config.max_document_text_size, 10 * 1024 * 1024);
    }

    #[test]
    fn test_new_config() {
        let config = ShardexConfig::new();
        assert_eq!(config, ShardexConfig::default());
    }

    #[test]
    fn test_builder_pattern() {
        let config = ShardexConfig::new()
            .directory_path("/tmp/test_index")
            .vector_size(512)
            .shard_size(5000)
            .shardex_segment_size(500)
            .wal_segment_size(2048)
            .batch_write_interval_ms(200)
            .default_slop_factor(5)
            .bloom_filter_size(2048)
            .max_document_text_size(20 * 1024 * 1024);

        assert_eq!(config.directory_path, PathBuf::from("/tmp/test_index"));
        assert_eq!(config.vector_size, 512);
        assert_eq!(config.shard_size, 5000);
        assert_eq!(config.shardex_segment_size, 500);
        assert_eq!(config.wal_segment_size, 2048);
        assert_eq!(config.batch_write_interval_ms, 200);
        assert_eq!(config.slop_factor_config.default_factor, 5);
        assert_eq!(config.bloom_filter_size, 2048);
        assert_eq!(config.max_document_text_size, 20 * 1024 * 1024);
    }

    #[test]
    fn test_default_config_validation() {
        let config = ShardexConfig::default();
        assert!(config.validate().is_ok());
    }

    #[test]
    fn test_build_with_valid_config() {
        let config = ShardexConfig::new()
            .vector_size(256)
            .shard_size(1000)
            .build();
        assert!(config.is_ok());
    }

    #[test]
    fn test_zero_vector_size_validation() {
        let config = ShardexConfig::new().vector_size(0);
        let result = config.validate();
        assert!(result.is_err());
        if let Err(ShardexError::Config(msg)) = result {
            assert_eq!(
                msg,
                "vector_size - must be greater than 0: Set vector_size to match your embedding model dimensions (e.g., 384 for sentence transformers, 1536 for OpenAI embeddings)"
            );
        } else {
            panic!("Expected Config error");
        }
    }

    #[test]
    fn test_zero_shard_size_validation() {
        let config = ShardexConfig::new().shard_size(0);
        let result = config.validate();
        assert!(result.is_err());
        if let Err(ShardexError::Config(msg)) = result {
            assert_eq!(
                msg,
                "shard_size - must be greater than 0: Set shard_size to control how many vectors per shard (recommended: 10000-100000 depending on memory constraints)"
            );
        } else {
            panic!("Expected Config error");
        }
    }

    #[test]
    fn test_zero_shardex_segment_size_validation() {
        let config = ShardexConfig::new().shardex_segment_size(0);
        let result = config.validate();
        assert!(result.is_err());
        if let Err(ShardexError::Config(msg)) = result {
            assert_eq!(
                msg,
                "shardex_segment_size - must be greater than 0: Set shardex_segment_size to control file segment sizes (recommended: 64MB-1GB)"
            );
        } else {
            panic!("Expected Config error");
        }
    }

    #[test]
    fn test_wal_segment_size_too_small_validation() {
        let config = ShardexConfig::new().wal_segment_size(512);
        let result = config.validate();
        assert!(result.is_err());
        if let Err(ShardexError::Config(msg)) = result {
            assert_eq!(
                msg,
                "wal_segment_size - value 512 bytes is too small for efficient WAL operations: Set wal_segment_size to at least 1024 bytes (recommended: 1MB-64MB)"
            );
        } else {
            panic!("Expected Config error");
        }
    }

    #[test]
    fn test_wal_segment_size_too_large_validation() {
        let config = ShardexConfig::new().wal_segment_size(2 * 1024 * 1024 * 1024);
        let result = config.validate();
        assert!(result.is_err());
        if let Err(ShardexError::Config(msg)) = result {
            assert_eq!(
                msg,
                "wal_segment_size - value 2147483648 bytes exceeds 1GB limit: Set wal_segment_size to 1GB or less to avoid memory and disk space issues"
            );
        } else {
            panic!("Expected Config error");
        }
    }

    #[test]
    fn test_zero_batch_write_interval_validation() {
        let config = ShardexConfig::new().batch_write_interval_ms(0);
        let result = config.validate();
        assert!(result.is_err());
        if let Err(ShardexError::Config(msg)) = result {
            assert_eq!(
                msg,
                "batch_write_interval_ms - must be greater than 0: Set batch_write_interval_ms to control how often batches are flushed (recommended: 100-1000ms)"
            );
        } else {
            panic!("Expected Config error");
        }
    }

    #[test]
    fn test_zero_slop_factor_validation() {
        let config = ShardexConfig::new().default_slop_factor(0);
        let result = config.validate();
        assert!(result.is_err());
        if let Err(ShardexError::Config(msg)) = result {
            assert_eq!(
                msg,
                "slop_factor_config.default_factor - must be greater than 0: Set default_factor to a positive integer (recommended: 3-10 for most use cases)"
            );
        } else {
            panic!("Expected Config error");
        }
    }

    #[test]
    fn test_zero_bloom_filter_size_validation() {
        let config = ShardexConfig::new().bloom_filter_size(0);
        let result = config.validate();
        assert!(result.is_err());
        if let Err(ShardexError::Config(msg)) = result {
            assert_eq!(
                msg,
                "bloom_filter_size - must be greater than 0: Set bloom_filter_size in bits (recommended: 1000000 for ~100k vectors with 1% false positive rate)"
            );
        } else {
            panic!("Expected Config error");
        }
    }

    #[test]
    fn test_empty_directory_path_validation() {
        let config = ShardexConfig {
            directory_path: PathBuf::new(),
            ..Default::default()
        };
        let result = config.validate();
        assert!(result.is_err());
        if let Err(ShardexError::Config(msg)) = result {
            assert_eq!(msg, "Directory path cannot be empty");
        } else {
            panic!("Expected Config error");
        }
    }

    #[test]
    fn test_zero_max_document_text_size_validation() {
        // 0 should now be valid (disables text storage)
        let config = ShardexConfig::new().max_document_text_size(0);
        let result = config.validate();
        assert!(result.is_ok());
    }

    #[test]
    fn test_max_document_text_size_below_minimum_validation() {
        let config = ShardexConfig::new().max_document_text_size(512);
        let result = config.validate();
        assert!(result.is_err());
        if let Err(ShardexError::Config(msg)) = result {
            assert_eq!(
                msg,
                "max_document_text_size - Size 512 bytes is below minimum 1024: Set max_document_text_size to 0 to disable text storage or at least 1024 bytes to enable"
            );
        } else {
            panic!("Expected Config error");
        }
    }

    #[test]
    fn test_max_document_text_size_at_minimum_boundary() {
        let config = ShardexConfig::new().max_document_text_size(1024);
        let result = config.validate();
        assert!(result.is_ok());
    }

    #[test]
    fn test_max_document_text_size_at_maximum_boundary() {
        let config = ShardexConfig::new().max_document_text_size(1024 * 1024 * 1024);
        let result = config.validate();
        assert!(result.is_ok());
    }

    #[test]
    fn test_max_document_text_size_too_large_validation() {
        let config = ShardexConfig::new().max_document_text_size(2 * 1024 * 1024 * 1024);
        let result = config.validate();
        assert!(result.is_err());
        if let Err(ShardexError::Config(msg)) = result {
            assert_eq!(
                msg,
                "max_document_text_size - Size 2147483648 bytes exceeds maximum 1073741824: Set max_document_text_size to at most 1073741824 bytes"
            );
        } else {
            panic!("Expected Config error");
        }
    }

    #[test]
    fn test_build_with_invalid_config() {
        let config = ShardexConfig::new().vector_size(0);
        let result = config.build();
        assert!(result.is_err());
    }

    #[test]
    fn test_config_clone() {
        let config1 = ShardexConfig::new().vector_size(256);
        let config2 = config1.clone();
        assert_eq!(config1, config2);
    }

    #[test]
    fn test_config_debug() {
        let config = ShardexConfig::new();
        let debug_str = format!("{:?}", config);
        assert!(debug_str.contains("ShardexConfig"));
        assert!(debug_str.contains("directory_path"));
        assert!(debug_str.contains("vector_size"));
    }

    #[test]
    fn test_pathbuf_conversion() {
        let config = ShardexConfig::new().directory_path("/home/user/index");
        assert_eq!(config.directory_path, PathBuf::from("/home/user/index"));

        let pathbuf = PathBuf::from("/var/lib/shardex");
        let config = ShardexConfig::new().directory_path(pathbuf.clone());
        assert_eq!(config.directory_path, pathbuf);
    }

    #[test]
    fn test_boundary_values() {
        // Test minimum valid WAL segment size
        let config = ShardexConfig::new().wal_segment_size(1024);
        assert!(config.validate().is_ok());

        // Test maximum valid WAL segment size
        let config = ShardexConfig::new().wal_segment_size(1024 * 1024 * 1024);
        assert!(config.validate().is_ok());
    }

    // Tests for SlopFactorConfig

    #[test]
    fn test_slop_factor_config_default() {
        let config = SlopFactorConfig::default();
        assert_eq!(config.default_factor, 3);
        assert_eq!(config.min_factor, 1);
        assert_eq!(config.max_factor, 100);
        assert!(!config.adaptive_enabled);
        assert_eq!(config.performance_threshold_ms, 100);
    }

    #[test]
    fn test_slop_factor_config_new() {
        let config = SlopFactorConfig::new();
        assert_eq!(config, SlopFactorConfig::default());
    }

    #[test]
    fn test_slop_factor_config_builder() {
        let config = SlopFactorConfig::new()
            .default_factor(5)
            .min_factor(2)
            .max_factor(50)
            .adaptive_enabled(true)
            .performance_threshold_ms(200);

        assert_eq!(config.default_factor, 5);
        assert_eq!(config.min_factor, 2);
        assert_eq!(config.max_factor, 50);
        assert!(config.adaptive_enabled);
        assert_eq!(config.performance_threshold_ms, 200);
    }

    #[test]
    fn test_slop_factor_config_validation() {
        let config = SlopFactorConfig::default();
        assert!(config.validate().is_ok());
    }

    #[test]
    fn test_slop_factor_config_zero_default_validation() {
        let config = SlopFactorConfig::new().default_factor(0);
        let result = config.validate();
        assert!(result.is_err());
        if let Err(ShardexError::Config(msg)) = result {
            assert_eq!(
                msg,
                "slop_factor_config.default_factor - must be greater than 0: Set default_factor to a positive integer (recommended: 3-10 for most use cases)"
            );
        } else {
            panic!("Expected Config error");
        }
    }

    #[test]
    fn test_slop_factor_config_zero_min_validation() {
        let config = SlopFactorConfig::new().min_factor(0);
        let result = config.validate();
        assert!(result.is_err());
        if let Err(ShardexError::Config(msg)) = result {
            assert_eq!(
                msg,
                "slop_factor_config.min_factor - must be greater than 0: Set min_factor to at least 1 (minimum valid slop factor)"
            );
        } else {
            panic!("Expected Config error");
        }
    }

    #[test]
    fn test_slop_factor_config_zero_max_validation() {
        let config = SlopFactorConfig::new().max_factor(0);
        let result = config.validate();
        assert!(result.is_err());
        if let Err(ShardexError::Config(msg)) = result {
            assert_eq!(
                msg,
                "slop_factor_config.max_factor - must be greater than 0: Set max_factor to a reasonable upper bound (recommended: 100 or less to avoid performance issues)"
            );
        } else {
            panic!("Expected Config error");
        }
    }

    #[test]
    fn test_slop_factor_config_min_greater_than_max_validation() {
        let config = SlopFactorConfig::new().min_factor(10).max_factor(5);
        let result = config.validate();
        assert!(result.is_err());
        if let Err(ShardexError::Config(msg)) = result {
            assert_eq!(
                msg,
                "slop_factor_config - min_factor (10) cannot be greater than max_factor (5): Ensure min_factor <= max_factor. For example: min_factor=1, max_factor=10"
            );
        } else {
            panic!("Expected Config error");
        }
    }

    #[test]
    fn test_slop_factor_config_default_out_of_range_validation() {
        let config = SlopFactorConfig::new()
            .default_factor(10)
            .min_factor(1)
            .max_factor(5);
        let result = config.validate();
        assert!(result.is_err());
        if let Err(ShardexError::Config(msg)) = result {
            assert_eq!(
                msg,
                "slop_factor_config.default_factor - value 10 is outside the allowed range [1, 5]: Set default_factor to a value between 1 and 5"
            );
        } else {
            panic!("Expected Config error");
        }
    }

    #[test]
    fn test_slop_factor_config_zero_performance_threshold_validation() {
        let config = SlopFactorConfig::new().performance_threshold_ms(0);
        let result = config.validate();
        assert!(result.is_err());
        if let Err(ShardexError::Config(msg)) = result {
            assert_eq!(
                msg,
                "slop_factor_config.performance_threshold_ms - must be greater than 0: Set performance_threshold_ms to a positive value in milliseconds (recommended: 50-200ms)"
            );
        } else {
            panic!("Expected Config error");
        }
    }

    #[test]
    fn test_slop_factor_config_build_valid() {
        let config = SlopFactorConfig::new().default_factor(5).build();
        assert!(config.is_ok());
    }

    #[test]
    fn test_slop_factor_config_build_invalid() {
        let config = SlopFactorConfig::new().default_factor(0).build();
        assert!(config.is_err());
    }

    #[test]
    fn test_calculate_optimal_slop_adaptive_disabled() {
        let config = SlopFactorConfig::new()
            .default_factor(5)
            .adaptive_enabled(false);
        let result = config.calculate_optimal_slop(384, 10);
        assert_eq!(result, 5);
    }

    #[test]
    fn test_calculate_optimal_slop_adaptive_enabled() {
        let config = SlopFactorConfig::new()
            .default_factor(3)
            .min_factor(1)
            .max_factor(10)
            .adaptive_enabled(true);

        let result = config.calculate_optimal_slop(384, 10);
        // Should be clamped within min/max range
        assert!((1..=10).contains(&result));

        // Larger vector size should generally result in higher slop
        let result_large = config.calculate_optimal_slop(1024, 10);
        assert!(result_large >= result);
    }

    #[test]
    fn test_calculate_optimal_slop_clamping() {
        let config = SlopFactorConfig::new()
            .default_factor(50)
            .min_factor(40)
            .max_factor(60)
            .adaptive_enabled(true);

        let result = config.calculate_optimal_slop(128, 5);
        assert!((40..=60).contains(&result));
    }

    #[test]
    fn test_shardex_config_with_slop_factor_config() {
        let slop_config = SlopFactorConfig::new()
            .default_factor(5)
            .adaptive_enabled(true);

        let config = ShardexConfig::new().slop_factor_config(slop_config);
        assert_eq!(config.slop_factor_config.default_factor, 5);
        assert!(config.slop_factor_config.adaptive_enabled);
    }

    #[test]
    fn test_slop_factor_config_clone() {
        let config1 = SlopFactorConfig::new().default_factor(7);
        let config2 = config1.clone();
        assert_eq!(config1, config2);
    }

    #[test]
    fn test_slop_factor_config_debug() {
        let config = SlopFactorConfig::new();
        let debug_str = format!("{:?}", config);
        assert!(debug_str.contains("SlopFactorConfig"));
        assert!(debug_str.contains("default_factor"));
        assert!(debug_str.contains("adaptive_enabled"));
    }
}