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
//! Test utilities for Shardex testing
//!
//! This module provides common utilities and helpers for testing Shardex components,
//! including RAII-based temporary directory management, test environment setup,
//! standardized test builders, and error handling utilities to eliminate duplication
//! across the test suite.

use crate::config::ShardexConfig;
use crate::error::ShardexError;
use crate::shardex_index::ShardexIndex;
use std::path::{Path, PathBuf};
use tempfile::TempDir;

/// Test environment macros to eliminate duplication
///
/// These macros provide standardized test setup patterns that automatically
/// handle TestEnvironment creation, variable naming consistency, and test name
/// string literal elimination.
/// Error handling utilities for tests
pub mod error {
    use crate::error::ShardexError;

    /// Assert that a Result contains an error of a specific ShardexError variant
    ///
    /// This macro provides a cleaner alternative to expect() in tests by validating
    /// that errors are of the expected type and providing clear assertion messages.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use shardex::test_utils::error::assert_error_type;
    /// use shardex::error::ShardexError;
    ///
    /// let result: Result<(), ShardexError> = Err(ShardexError::Config("test".to_string()));
    /// assert_error_type!(result, Config);
    /// ```
    #[macro_export]
    macro_rules! assert_error_type {
        ($result:expr, $variant:ident) => {
            match $result {
                Ok(val) => panic!(
                    "Expected error of type {}, but got Ok({:?})",
                    stringify!($variant),
                    val
                ),
                Err(ref err) => {
                    if !matches!(err, ShardexError::$variant(..)) {
                        panic!(
                            "Expected error of type {}, but got: {}",
                            stringify!($variant),
                            err
                        );
                    }
                }
            }
        };
        ($result:expr, $variant:ident { $($field:ident),+ }) => {
            match $result {
                Ok(val) => panic!(
                    "Expected error of type {} with fields {}, but got Ok({:?})",
                    stringify!($variant),
                    stringify!($($field),+),
                    val
                ),
                Err(ref err) => {
                    if !matches!(err, ShardexError::$variant { $($field: _),+ }) {
                        panic!(
                            "Expected error of type {} with fields {}, but got: {}",
                            stringify!($variant),
                            stringify!($($field),+),
                            err
                        );
                    }
                }
            }
        };
    }

    /// Assert that an error message contains specific text
    ///
    /// This macro validates that error messages contain expected information,
    /// useful for testing error context and recovery suggestions.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use shardex::test_utils::error::assert_error_contains;
    /// use shardex::error::ShardexError;
    ///
    /// let result: Result<(), ShardexError> = Err(ShardexError::Config("missing field: vector_dim".to_string()));
    /// assert_error_contains!(result, "missing field");
    /// assert_error_contains!(result, "vector_dim");
    /// ```
    #[macro_export]
    macro_rules! assert_error_contains {
        ($result:expr, $text:expr) => {
            match $result {
                Ok(val) => panic!(
                    "Expected error containing '{}', but got Ok({:?})",
                    $text,
                    val
                ),
                Err(ref err) => {
                    let error_str = err.to_string();
                    if !error_str.contains($text) {
                        panic!(
                            "Expected error to contain '{}', but error was: '{}'",
                            $text,
                            error_str
                        );
                    }
                }
            }
        };
        ($result:expr, $($text:expr),+) => {
            $(assert_error_contains!($result, $text);)+
        };
    }

    /// Get an error from a Result, panicking with a helpful message if Result is Ok
    ///
    /// This function provides a cleaner alternative to unwrap_err() by providing
    /// context about what error was expected.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use shardex::test_utils::error::expect_error;
    /// use shardex::error::ShardexError;
    ///
    /// let result: Result<(), ShardexError> = Err(ShardexError::Config("test".to_string()));
    /// let error = expect_error(result, "configuration validation should fail");
    /// ```
    pub fn expect_error<T, E>(result: Result<T, E>, context: &str) -> E
    where
        T: std::fmt::Debug,
    {
        match result {
            Ok(val) => panic!("Expected error ({}), but got Ok({:?})", context, val),
            Err(err) => err,
        }
    }

    /// Assert that a Result is Ok and return the value, with helpful error context
    ///
    /// This function provides a cleaner alternative to unwrap() by providing
    /// context about what operation should have succeeded.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use shardex::test_utils::error::expect_success;
    ///
    /// let result: Result<i32, String> = Ok(42);
    /// let value = expect_success(result, "arithmetic operation should succeed");
    /// assert_eq!(value, 42);
    /// ```
    pub fn expect_success<T, E>(result: Result<T, E>, context: &str) -> T
    where
        E: std::fmt::Display,
    {
        match result {
            Ok(val) => val,
            Err(err) => panic!("Expected success ({}), but got error: {}", context, err),
        }
    }

    /// Create a test error with context for validation
    ///
    /// Helper function for creating errors in tests that need to validate
    /// error handling and context preservation.
    pub fn create_test_io_error(message: &str) -> std::io::Error {
        std::io::Error::new(std::io::ErrorKind::Other, message)
    }

    /// Create a test ShardexError for validation
    ///
    /// Helper function for creating ShardexErrors in tests.
    pub fn create_test_shardex_error(variant: &str, message: &str) -> ShardexError {
        match variant {
            "config" => ShardexError::Config(message.to_string()),
            "memory_mapping" => ShardexError::MemoryMapping(message.to_string()),
            "wal" => ShardexError::Wal(message.to_string()),
            "shard" => ShardexError::Shard(message.to_string()),
            "search" => ShardexError::Search(message.to_string()),
            "corruption" => ShardexError::Corruption(message.to_string()),
            "text_corruption" => ShardexError::TextCorruption(message.to_string()),
            _ => panic!("Unknown test error variant: {}", variant),
        }
    }

    /// Assert that error has proper context information
    ///
    /// This function validates that errors contain expected context information
    /// like file paths, operation names, and recovery suggestions.
    pub fn assert_error_context(error: &ShardexError, expected_contexts: &[&str]) {
        let error_str = error.to_string();
        for context in expected_contexts {
            if !error_str.contains(context) {
                panic!(
                    "Expected error to contain context '{}', but error was: '{}'",
                    context, error_str
                );
            }
        }
    }

    /// Assert that error chain is properly preserved
    ///
    /// This function validates that error causality is preserved through
    /// error transformations and context additions.
    pub fn assert_error_causality(error: &ShardexError, expected_causes: &[&str]) {
        let error_str = error.to_string();
        for cause in expected_causes {
            if !error_str.contains(cause) {
                panic!(
                    "Expected error to contain cause '{}', but error was: '{}'",
                    cause, error_str
                );
            }
        }
    }
}

/// RAII-based test environment for isolated testing
///
/// TestEnvironment provides each test with its own temporary directory that is
/// automatically cleaned up when the test completes. This ensures tests run
/// in isolation without interfering with each other.
///
/// # Usage
///
/// ```rust
/// use shardex::test_utils::TestEnvironment;
///
/// fn my_test() {
///     let _test_env = TestEnvironment::new("my_test");
///     // Use _test_env.temp_dir.path() for file operations
///     // Directory is automatically cleaned up when _test_env is dropped
/// }
/// ```
pub struct TestEnvironment {
    pub temp_dir: TempDir,
    pub test_name: String,
}

impl TestEnvironment {
    /// Create a new test environment with the given test name
    ///
    /// # Arguments
    /// * `test_name` - Name of the test, used for debugging and diagnostics
    ///
    /// # Panics
    /// Panics if unable to create temporary directory
    pub fn new(test_name: &str) -> Self {
        let temp_dir =
            TempDir::new().unwrap_or_else(|e| panic!("Failed to create temp dir for test {}: {}", test_name, e));

        Self {
            temp_dir,
            test_name: test_name.to_string(),
        }
    }

    /// Get the path to the temporary directory
    pub fn path(&self) -> &Path {
        self.temp_dir.path()
    }

    /// Get a PathBuf to the temporary directory
    pub fn path_buf(&self) -> PathBuf {
        self.temp_dir.path().to_path_buf()
    }

    /// Create a subdirectory within the test environment
    ///
    /// # Arguments
    /// * `name` - Name of the subdirectory to create
    ///
    /// # Returns
    /// PathBuf to the created subdirectory
    pub fn create_subdir(&self, name: &str) -> std::io::Result<PathBuf> {
        let subdir_path = self.temp_dir.path().join(name);
        std::fs::create_dir_all(&subdir_path)?;
        Ok(subdir_path)
    }

    /// Get the test name
    pub fn name(&self) -> &str {
        &self.test_name
    }
}

/// Helper function to create a standard TempDir for tests
///
/// Eliminates duplication of TempDir::new().unwrap() across tests
/// and provides standardized error message.
pub fn create_temp_dir_for_test(test_name: &str) -> TempDir {
    TempDir::new().unwrap_or_else(|e| {
        panic!(
            "{} for test {}: {}",
            test_error_messages::FAILED_TO_CREATE_TEMP_DIR,
            test_name,
            e
        )
    })
}

impl Drop for TestEnvironment {
    fn drop(&mut self) {
        // TempDir handles cleanup automatically
        // Debug logging can be added here if needed during development
    }
}

/// Test constants to eliminate magic numbers across test suite
pub mod test_constants {
    pub const DEFAULT_VECTOR_SIZE: usize = 128;
    pub const SMALL_VECTOR_SIZE: usize = 64;
    pub const LARGE_VECTOR_SIZE: usize = 384;
    pub const DEFAULT_SHARD_SIZE: usize = 100;
    pub const LARGE_SHARD_SIZE: usize = 1000;
    pub const DEFAULT_TEST_CAPACITY: usize = 100;
}

/// Standardized error messages for consistent test failure reporting
pub mod test_error_messages {
    pub const FAILED_TO_CREATE_INDEX: &str = "Failed to create test index";
    pub const FAILED_TO_CREATE_CONFIG: &str = "Failed to create test config";
    pub const FAILED_TO_CREATE_WRITER: &str = "Failed to create test writer";
    pub const FAILED_TO_CREATE_STORAGE: &str = "Failed to create test storage";
    pub const FAILED_TO_CREATE_TEMP_DIR: &str = "Failed to create temp dir for test";
    pub const FAILED_TO_CREATE_COW_INDEX: &str = "Failed to create COW index";
}

/// Builder pattern for standardized test setup
///
/// Eliminates duplication of TestEnvironment creation, ShardexConfig setup,
/// and index initialization across the test suite. Provides a fluent API
/// for configuring test parameters while maintaining sensible defaults.
///
/// # Usage
///
/// ```rust
/// use shardex::test_utils::TestSetupBuilder;
///
/// // Basic setup with defaults
/// let (test_env, config) = TestSetupBuilder::new("my_test").build();
///
/// // Custom configuration
/// let (test_env, config, index) = TestSetupBuilder::new("my_test")
///     .with_vector_size(256)
///     .with_shard_size(500)
///     .build_with_index()
///     .expect("Failed to create index");
/// ```
pub struct TestSetupBuilder {
    test_name: String,
    vector_size: usize,
    shard_size: usize,
    directory_path: Option<PathBuf>,
}

impl TestSetupBuilder {
    /// Create a new test setup builder with the given test name
    ///
    /// Uses default values:
    /// - vector_size: 128
    /// - shard_size: 100
    /// - directory_path: None (will create temporary directory)
    pub fn new(test_name: &str) -> Self {
        Self {
            test_name: test_name.to_string(),
            vector_size: test_constants::DEFAULT_VECTOR_SIZE,
            shard_size: test_constants::DEFAULT_SHARD_SIZE,
            directory_path: None,
        }
    }

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

    /// Set the shard size for the test configuration
    pub fn with_shard_size(mut self, size: usize) -> Self {
        self.shard_size = size;
        self
    }

    /// Set a custom directory path (primarily for testing directory handling)
    pub fn with_directory_path(mut self, path: PathBuf) -> Self {
        self.directory_path = Some(path);
        self
    }

    /// Build test environment and configuration without creating index
    ///
    /// Returns TestEnvironment and ShardexConfig ready for use.
    /// Use this when you need to customize index creation or don't need an index.
    pub fn build(self) -> (TestEnvironment, ShardexConfig) {
        let test_env = TestEnvironment::new(&self.test_name);

        let directory_path = self.directory_path.unwrap_or_else(|| test_env.path_buf());

        let config = ShardexConfig::new()
            .directory_path(directory_path)
            .vector_size(self.vector_size)
            .shard_size(self.shard_size);

        (test_env, config)
    }

    /// Build test environment, configuration, and index
    ///
    /// Returns TestEnvironment, ShardexConfig, and created ShardexIndex.
    /// This is the most common pattern for tests that need a working index.
    pub fn build_with_index(self) -> Result<(TestEnvironment, ShardexConfig, ShardexIndex), ShardexError> {
        let (test_env, config) = self.build();
        let index = ShardexIndex::create(config.clone()).map_err(|e| ShardexError::InvalidInput {
            field: "index_creation".to_string(),
            reason: format!("{}: {}", test_error_messages::FAILED_TO_CREATE_INDEX, e),
            suggestion: "Check directory permissions and disk space".to_string(),
        })?;

        Ok((test_env, config, index))
    }

    /// Build with small vector size (64) - convenience method for performance tests
    pub fn small(test_name: &str) -> Self {
        Self::new(test_name).with_vector_size(test_constants::SMALL_VECTOR_SIZE)
    }

    /// Build with large vector size (384) - convenience method for capacity tests
    pub fn large(test_name: &str) -> Self {
        Self::new(test_name)
            .with_vector_size(test_constants::LARGE_VECTOR_SIZE)
            .with_shard_size(test_constants::LARGE_SHARD_SIZE)
    }

    /// Get the test name
    pub fn name(&self) -> &str {
        &self.test_name
    }
}

/// Domain-specific test environment builders for common patterns
///
/// These builders provide specialized test setup for specific Shardex components,
/// eliminating duplication while providing type-safe, ergonomic test initialization.
/// Shardex-specific test environment builder
///
/// Provides convenience methods for creating test environments specifically
/// tailored for Shardex testing, with pre-configured defaults and patterns
/// commonly used in shardex tests.
pub struct ShardexTestEnv {
    pub env: TestEnvironment,
    pub config: ShardexConfig,
}

impl ShardexTestEnv {
    /// Create a new Shardex test environment with standard defaults
    ///
    /// Automatically configures:
    /// - TestEnvironment with the given test name
    /// - ShardexConfig with appropriate defaults for testing
    ///
    /// # Arguments
    /// * `test_name` - Name of the test, will be used as TestEnvironment name
    pub fn new(test_name: &str) -> Self {
        let env = TestEnvironment::new(test_name);
        let config = ShardexConfig::new()
            .directory_path(env.path())
            .vector_size(test_constants::DEFAULT_VECTOR_SIZE)
            .shard_size(test_constants::DEFAULT_SHARD_SIZE);

        Self { env, config }
    }

    /// Create with custom vector size
    pub fn with_vector_size(mut self, size: usize) -> Self {
        self.config = self.config.vector_size(size);
        self
    }

    /// Create with custom shard size
    pub fn with_shard_size(mut self, size: usize) -> Self {
        self.config = self.config.shard_size(size);
        self
    }

    /// Create with small configuration (for performance tests)
    pub fn small(test_name: &str) -> Self {
        Self::new(test_name).with_vector_size(test_constants::SMALL_VECTOR_SIZE)
    }

    /// Create with large configuration (for capacity tests)
    pub fn large(test_name: &str) -> Self {
        Self::new(test_name)
            .with_vector_size(test_constants::LARGE_VECTOR_SIZE)
            .with_shard_size(test_constants::LARGE_SHARD_SIZE)
    }

    /// Build and create a ShardexIndex
    pub fn build_with_index(self) -> Result<(TestEnvironment, ShardexConfig, ShardexIndex), ShardexError> {
        let index = ShardexIndex::create(self.config.clone()).map_err(|e| ShardexError::InvalidInput {
            field: "index_creation".to_string(),
            reason: format!("{}: {}", test_error_messages::FAILED_TO_CREATE_INDEX, e),
            suggestion: "Check directory permissions and disk space".to_string(),
        })?;

        Ok((self.env, self.config, index))
    }

    /// Get reference to the test environment
    pub fn env(&self) -> &TestEnvironment {
        &self.env
    }

    /// Get reference to the config
    pub fn config(&self) -> &ShardexConfig {
        &self.config
    }
}

/// Concurrent test environment builder
///
/// Specialized for testing concurrent operations and COW index patterns.
/// Provides utilities for setting up concurrent test scenarios with
/// appropriate configurations and test data.
pub struct ConcurrentTestEnv {
    pub env: TestEnvironment,
    pub config: ShardexConfig,
}

impl ConcurrentTestEnv {
    /// Create a new concurrent test environment
    pub fn new(test_name: &str) -> Self {
        let env = TestEnvironment::new(test_name);
        let config = ShardexConfig::new()
            .directory_path(env.path())
            .vector_size(test_constants::DEFAULT_VECTOR_SIZE)
            .shard_size(test_constants::DEFAULT_SHARD_SIZE);

        Self { env, config }
    }

    /// Create with high concurrency configuration
    pub fn high_concurrency(test_name: &str) -> Self {
        Self::new(test_name).with_shard_size(test_constants::LARGE_SHARD_SIZE)
    }

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

    /// Set custom shard size
    pub fn with_shard_size(mut self, size: usize) -> Self {
        self.config = self.config.shard_size(size);
        self
    }

    /// Build with COW index ready for concurrent operations
    pub async fn build_with_cow_index(
        self,
    ) -> Result<(TestEnvironment, ShardexConfig, crate::cow_index::CowShardexIndex), ShardexError> {
        let index = ShardexIndex::create(self.config.clone()).map_err(|e| ShardexError::InvalidInput {
            field: "index_creation".to_string(),
            reason: format!("{}: {}", test_error_messages::FAILED_TO_CREATE_INDEX, e),
            suggestion: "Check directory permissions and disk space".to_string(),
        })?;

        let cow_index = crate::cow_index::CowShardexIndex::new(index);
        Ok((self.env, self.config, cow_index))
    }

    /// Build with concurrent Shardex ready for testing
    pub async fn build_with_concurrent(
        self,
    ) -> Result<(TestEnvironment, ShardexConfig, crate::concurrent::ConcurrentShardex), ShardexError> {
        let (env, config, cow_index) = self.build_with_cow_index().await?;
        let concurrent = crate::concurrent::ConcurrentShardex::new(cow_index);
        Ok((env, config, concurrent))
    }
}

/// WAL test environment builder
///
/// Specialized for testing Write-Ahead Log functionality with appropriate
/// configurations for WAL operations, replay testing, and recovery scenarios.
pub struct WalTestEnv {
    pub env: TestEnvironment,
    pub config: ShardexConfig,
}

impl WalTestEnv {
    /// Default WAL segment size for testing (1MB)
    const DEFAULT_WAL_SEGMENT_SIZE: usize = 1024 * 1024;

    /// Create a new WAL test environment
    pub fn new(test_name: &str) -> Self {
        let env = TestEnvironment::new(test_name);
        let config = ShardexConfig::new()
            .directory_path(env.path())
            .vector_size(test_constants::DEFAULT_VECTOR_SIZE)
            .shard_size(test_constants::DEFAULT_SHARD_SIZE);

        Self { env, config }
    }

    /// Get the WAL directory path
    pub fn wal_path(&self) -> PathBuf {
        self.env.path().join("wal")
    }

    /// Create WAL directory if it doesn't exist
    pub fn ensure_wal_dir(&self) -> std::io::Result<PathBuf> {
        let wal_path = self.wal_path();
        std::fs::create_dir_all(&wal_path)?;
        Ok(wal_path)
    }

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

    /// Set custom shard size
    pub fn with_shard_size(mut self, size: usize) -> Self {
        self.config = self.config.shard_size(size);
        self
    }

    /// Build with WAL manager ready for testing
    pub fn build_with_wal_manager(
        self,
    ) -> Result<(TestEnvironment, ShardexConfig, crate::wal::WalManager), ShardexError> {
        let _wal_path = self
            .ensure_wal_dir()
            .map_err(|e| ShardexError::Wal(format!("Failed to create WAL directory: {}", e)))?;

        let layout = crate::layout::DirectoryLayout::new(self.env.path());
        let wal_manager = crate::wal::WalManager::new(layout, Self::DEFAULT_WAL_SEGMENT_SIZE);

        Ok((self.env, self.config, wal_manager))
    }
}

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

    #[test]
    fn test_environment_creation() {
        let test_env = TestEnvironment::new("test_environment_creation");

        assert_eq!(test_env.name(), "test_environment_creation");
        assert!(test_env.path().exists());
        assert!(test_env.path().is_dir());
    }

    #[test]
    fn test_subdir_creation() {
        let test_env = TestEnvironment::new("test_subdir_creation");

        let subdir = test_env.create_subdir("test_sub").unwrap();
        assert!(subdir.exists());
        assert!(subdir.is_dir());
        assert_eq!(subdir.file_name().unwrap(), "test_sub");
    }

    #[test]
    fn test_file_operations() {
        let test_env = TestEnvironment::new("test_file_operations");

        let test_file = test_env.path().join("test.txt");
        fs::write(&test_file, "test content").unwrap();

        assert!(test_file.exists());
        let content = fs::read_to_string(&test_file).unwrap();
        assert_eq!(content, "test content");
    }

    #[test]
    fn test_path_methods() {
        let test_env = TestEnvironment::new("test_path_methods");

        let path = test_env.path();
        let path_buf = test_env.path_buf();

        assert_eq!(path, path_buf.as_path());
        assert!(path.exists());
        assert!(path_buf.exists());
    }

    #[test]
    fn test_setup_builder_basic() {
        let (test_env, config) = TestSetupBuilder::new("test_setup_builder_basic").build();

        assert_eq!(test_env.name(), "test_setup_builder_basic");
        assert!(test_env.path().exists());
        assert_eq!(config.vector_size, test_constants::DEFAULT_VECTOR_SIZE);
        assert_eq!(config.shard_size, test_constants::DEFAULT_SHARD_SIZE);
    }

    #[test]
    fn test_setup_builder_custom_config() {
        let (test_env, config) = TestSetupBuilder::new("test_setup_builder_custom")
            .with_vector_size(256)
            .with_shard_size(500)
            .build();

        assert_eq!(test_env.name(), "test_setup_builder_custom");
        assert_eq!(config.vector_size, 256);
        assert_eq!(config.shard_size, 500);
    }

    #[test]
    fn test_setup_builder_with_index() {
        let result = TestSetupBuilder::new("test_setup_builder_with_index").build_with_index();

        assert!(result.is_ok());
        let (test_env, config, index) = result.unwrap();

        assert_eq!(test_env.name(), "test_setup_builder_with_index");
        assert_eq!(config.vector_size, test_constants::DEFAULT_VECTOR_SIZE);
        assert_eq!(index.shard_count(), 0); // New index starts empty
    }

    #[test]
    fn test_setup_builder_small_convenience() {
        let (test_env, config) = TestSetupBuilder::small("test_small").build();

        assert_eq!(test_env.name(), "test_small");
        assert_eq!(config.vector_size, test_constants::SMALL_VECTOR_SIZE);
        assert_eq!(config.shard_size, test_constants::DEFAULT_SHARD_SIZE);
    }

    #[test]
    fn test_setup_builder_large_convenience() {
        let (test_env, config) = TestSetupBuilder::large("test_large").build();

        assert_eq!(test_env.name(), "test_large");
        assert_eq!(config.vector_size, test_constants::LARGE_VECTOR_SIZE);
        assert_eq!(config.shard_size, test_constants::LARGE_SHARD_SIZE);
    }

    #[test]
    fn test_create_temp_dir_for_test() {
        let temp_dir = create_temp_dir_for_test("test_temp_dir_creation");

        assert!(temp_dir.path().exists());
        assert!(temp_dir.path().is_dir());
    }

    // Tests for new domain-specific test environment builders

    #[test]
    fn test_shardex_test_env_basic() {
        let test_env = ShardexTestEnv::new("test_shardex_env_basic");

        assert_eq!(test_env.env.name(), "test_shardex_env_basic");
        assert!(test_env.env.path().exists());
        assert_eq!(test_env.config.vector_size, test_constants::DEFAULT_VECTOR_SIZE);
        assert_eq!(test_env.config.shard_size, test_constants::DEFAULT_SHARD_SIZE);
        assert_eq!(test_env.config.directory_path, test_env.env.path());
    }

    #[test]
    fn test_shardex_test_env_with_custom_vector_size() {
        let test_env = ShardexTestEnv::new("test_shardex_custom_vector").with_vector_size(256);

        assert_eq!(test_env.config.vector_size, 256);
        assert_eq!(test_env.config.shard_size, test_constants::DEFAULT_SHARD_SIZE);
    }

    #[test]
    fn test_shardex_test_env_with_custom_shard_size() {
        let test_env = ShardexTestEnv::new("test_shardex_custom_shard").with_shard_size(500);

        assert_eq!(test_env.config.vector_size, test_constants::DEFAULT_VECTOR_SIZE);
        assert_eq!(test_env.config.shard_size, 500);
    }

    #[test]
    fn test_shardex_test_env_large() {
        let test_env = ShardexTestEnv::large("test_shardex_large");

        assert_eq!(test_env.config.shard_size, test_constants::LARGE_SHARD_SIZE);
        assert_eq!(test_env.config.vector_size, test_constants::LARGE_VECTOR_SIZE);
    }

    #[test]
    fn test_concurrent_test_env_basic() {
        let test_env = ConcurrentTestEnv::new("test_concurrent_env_basic");

        assert_eq!(test_env.env.name(), "test_concurrent_env_basic");
        assert!(test_env.env.path().exists());
        assert_eq!(test_env.config.vector_size, test_constants::DEFAULT_VECTOR_SIZE);
        assert_eq!(test_env.config.shard_size, test_constants::DEFAULT_SHARD_SIZE);
    }

    #[test]
    fn test_concurrent_test_env_high_concurrency() {
        let test_env = ConcurrentTestEnv::high_concurrency("test_concurrent_high");

        assert_eq!(test_env.config.shard_size, test_constants::LARGE_SHARD_SIZE);
        assert_eq!(test_env.config.vector_size, test_constants::DEFAULT_VECTOR_SIZE);
    }

    #[test]
    fn test_concurrent_test_env_with_custom_sizes() {
        let test_env = ConcurrentTestEnv::new("test_concurrent_custom")
            .with_vector_size(512)
            .with_shard_size(750);

        assert_eq!(test_env.config.vector_size, 512);
        assert_eq!(test_env.config.shard_size, 750);
    }

    #[test]
    fn test_wal_test_env_basic() {
        let test_env = WalTestEnv::new("test_wal_env_basic");

        assert_eq!(test_env.env.name(), "test_wal_env_basic");
        assert!(test_env.env.path().exists());
        assert_eq!(test_env.config.vector_size, test_constants::DEFAULT_VECTOR_SIZE);
        assert_eq!(test_env.config.shard_size, test_constants::DEFAULT_SHARD_SIZE);
    }

    #[test]
    fn test_wal_test_env_with_custom_vector_size() {
        let test_env = WalTestEnv::new("test_wal_custom_vector").with_vector_size(384);

        assert_eq!(test_env.config.vector_size, 384);
    }

    #[test]
    fn test_wal_test_env_with_custom_shard_size() {
        let test_env = WalTestEnv::new("test_wal_custom_shard").with_shard_size(600);

        assert_eq!(test_env.config.shard_size, 600);
    }

    #[test]
    fn test_wal_test_env_ensure_wal_dir() {
        let test_env = WalTestEnv::new("test_wal_ensure_dir");

        let result = test_env.ensure_wal_dir();
        assert!(result.is_ok());

        let wal_dir = result.unwrap();
        assert!(wal_dir.exists());
        assert!(wal_dir.is_dir());
    }

    #[test]
    fn test_wal_test_env_build_with_wal_manager() {
        let test_env = WalTestEnv::new("test_wal_build_manager");

        let result = test_env.build_with_wal_manager();
        assert!(result.is_ok());

        let (_env, _config, _wal_manager) = result.unwrap();
        // WAL manager creation should succeed with valid directory layout
    }

    #[tokio::test]
    async fn test_concurrent_test_env_build_with_cow_index() {
        let test_env = ConcurrentTestEnv::new("test_concurrent_cow_index");

        let result = test_env.build_with_cow_index().await;
        assert!(result.is_ok());

        let (_env, config, _cow_index) = result.unwrap();
        assert_eq!(config.vector_size, test_constants::DEFAULT_VECTOR_SIZE);
    }

    #[tokio::test]
    async fn test_concurrent_test_env_build_with_concurrent() {
        let test_env = ConcurrentTestEnv::new("test_concurrent_full_build");

        let result = test_env.build_with_concurrent().await;
        assert!(result.is_ok());

        let (_env, config, _concurrent_shardex) = result.unwrap();
        assert_eq!(config.vector_size, test_constants::DEFAULT_VECTOR_SIZE);
    }
}