torsh-distributed 0.1.2

Distributed training and inference for ToRSh
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
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
//! Distributed store for process coordination
//!
//! The distributed store provides a key-value store that all processes
//! can access to coordinate initialization and share information during
//! distributed training.

use crate::{TorshDistributedError, TorshResult};
use log::{debug, info, warn};
use dashmap::DashMap;
use parking_lot::RwLock;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::net::IpAddr;
use std::sync::Arc;
use std::time::{Duration, Instant};

#[cfg(feature = "redis")]
use redis::{AsyncCommands, Client as RedisClient};

/// Timeout for store operations
const DEFAULT_TIMEOUT: Duration = Duration::from_secs(30);

/// A value stored in the distributed store
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StoreValue {
    data: Vec<u8>,
    timestamp: u64,
}

impl StoreValue {
    fn new(data: Vec<u8>) -> Self {
        Self {
            data,
            timestamp: std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .expect("time should be after UNIX_EPOCH")
                .as_secs(),
        }
    }

    pub fn data(&self) -> &[u8] {
        &self.data
    }

    pub fn timestamp(&self) -> u64 {
        self.timestamp
    }
}

/// Store backend types
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StoreBackend {
    /// In-memory store (for testing)
    Memory,
    /// File-based store
    File,
    /// TCP-based store
    Tcp,
    /// Redis-based store
    Redis,
}

/// Configuration for the distributed store
#[derive(Debug, Clone)]
pub struct StoreConfig {
    /// Backend type
    pub backend: StoreBackend,
    /// Master address for TCP store
    pub master_addr: Option<IpAddr>,
    /// Master port for TCP store
    pub master_port: Option<u16>,
    /// File path for file-based store
    pub file_path: Option<String>,
    /// Redis URL for Redis store
    pub redis_url: Option<String>,
    /// Timeout for operations
    pub timeout: Duration,
    /// Number of retries for failed operations
    pub max_retries: u32,
}

impl Default for StoreConfig {
    fn default() -> Self {
        Self {
            backend: StoreBackend::Memory,
            master_addr: None,
            master_port: None,
            file_path: None,
            redis_url: None,
            timeout: DEFAULT_TIMEOUT,
            max_retries: 3,
        }
    }
}

/// Trait for distributed store backends
#[async_trait::async_trait]
pub trait Store: Send + Sync {
    /// Set a key-value pair
    async fn set(&self, key: &str, value: &[u8]) -> TorshResult<()>;

    /// Get a value by key
    async fn get(&self, key: &str) -> TorshResult<Option<Vec<u8>>>;

    /// Wait for a key to become available
    async fn wait(&self, keys: &[String]) -> TorshResult<()>;

    /// Delete a key
    async fn delete(&self, key: &str) -> TorshResult<()>;

    /// Get the number of keys in the store
    async fn num_keys(&self) -> TorshResult<usize>;

    /// Check if a key exists
    async fn contains(&self, key: &str) -> TorshResult<bool>;

    /// Set a key with expiration
    async fn set_with_expiry(&self, key: &str, value: &[u8], ttl: Duration) -> TorshResult<()>;

    /// Atomic compare and swap
    async fn compare_and_swap(
        &self,
        key: &str,
        expected: Option<&[u8]>,
        value: &[u8],
    ) -> TorshResult<bool>;

    /// Add to a numeric value (atomic)
    async fn add(&self, key: &str, value: i64) -> TorshResult<i64>;
}

/// In-memory store implementation
#[derive(Debug)]
pub struct MemoryStore {
    data: Arc<DashMap<String, StoreValue>>,
}

impl MemoryStore {
    pub fn new() -> Self {
        Self {
            data: Arc::new(DashMap::new()),
        }
    }
}

impl Default for MemoryStore {
    fn default() -> Self {
        Self::new()
    }
}

#[async_trait::async_trait]
impl Store for MemoryStore {
    async fn set(&self, key: &str, value: &[u8]) -> TorshResult<()> {
        let store_value = StoreValue::new(value.to_vec());
        self.data.insert(key.to_string(), store_value);
        Ok(())
    }

    async fn get(&self, key: &str) -> TorshResult<Option<Vec<u8>>> {
        Ok(self.data.get(key).map(|v| v.data.clone()))
    }

    async fn wait(&self, keys: &[String]) -> TorshResult<()> {
        let start = Instant::now();

        loop {
            let all_present = keys.iter().all(|key| self.data.contains_key(key));

            if all_present {
                return Ok(());
            }

            if start.elapsed() > DEFAULT_TIMEOUT {
                return Err(TorshDistributedError::communication_error(
                    "Store wait",
                    "Timeout waiting for keys",
                )
                .into());
            }

            tokio::time::sleep(Duration::from_millis(10)).await;
        }
    }

    async fn delete(&self, key: &str) -> TorshResult<()> {
        self.data.remove(key);
        Ok(())
    }

    async fn num_keys(&self) -> TorshResult<usize> {
        Ok(self.data.len())
    }

    async fn contains(&self, key: &str) -> TorshResult<bool> {
        Ok(self.data.contains_key(key))
    }

    async fn set_with_expiry(&self, key: &str, value: &[u8], _ttl: Duration) -> TorshResult<()> {
        // Memory store doesn't support TTL, just set normally
        self.set(key, value).await
    }

    async fn compare_and_swap(
        &self,
        key: &str,
        expected: Option<&[u8]>,
        value: &[u8],
    ) -> TorshResult<bool> {
        match expected {
            Some(expected_val) => {
                if let Some(current) = self.data.get(key) {
                    if current.data == expected_val {
                        let store_value = StoreValue::new(value.to_vec());
                        self.data.insert(key.to_string(), store_value);
                        Ok(true)
                    } else {
                        Ok(false)
                    }
                } else {
                    Ok(false)
                }
            }
            None => {
                // Expected value is None, so set only if key doesn't exist
                if self.data.contains_key(key) {
                    Ok(false)
                } else {
                    let store_value = StoreValue::new(value.to_vec());
                    self.data.insert(key.to_string(), store_value);
                    Ok(true)
                }
            }
        }
    }

    async fn add(&self, key: &str, value: i64) -> TorshResult<i64> {
        let new_value = if let Some(existing) = self.data.get(key) {
            let current = i64::from_le_bytes(existing.data[..8].try_into().map_err(|_| {
                TorshDistributedError::invalid_argument(
                    "value",
                    "Failed to convert stored bytes to i64",
                    "8 bytes representing a valid i64 value",
                )
            })?);
            current + value
        } else {
            value
        };

        let store_value = StoreValue::new(new_value.to_le_bytes().to_vec());
        self.data.insert(key.to_string(), store_value);
        Ok(new_value)
    }
}

/// File-based store implementation
#[derive(Debug)]
pub struct FileStore {
    file_path: String,
    data: Arc<RwLock<HashMap<String, StoreValue>>>,
}

impl FileStore {
    pub fn new(file_path: String) -> TorshResult<Self> {
        let store = Self {
            file_path,
            data: Arc::new(RwLock::new(HashMap::new())),
        };

        // Try to load existing data
        if let Err(_) = store.load_from_file() {
            // If loading fails, start with empty store
        }

        Ok(store)
    }

    fn load_from_file(&self) -> TorshResult<()> {
        if std::path::Path::new(&self.file_path).exists() {
            let contents = std::fs::read_to_string(&self.file_path).map_err(|e| {
                TorshDistributedError::backend_error(
                    "FileStore",
                    format!("Failed to read store file: {}", e),
                )
            })?;

            let data: HashMap<String, StoreValue> =
                serde_json::from_str(&contents).map_err(|e| {
                    TorshDistributedError::backend_error(
                        "FileStore",
                        format!("Failed to parse store file: {}", e),
                    )
                })?;

            *self.data.write() = data;
        }
        Ok(())
    }

    fn save_to_file(&self) -> TorshResult<()> {
        let data = self.data.read();
        let contents = serde_json::to_string_pretty(&*data).map_err(|e| {
            TorshDistributedError::backend_error(
                "FileStore",
                format!("Failed to serialize store: {}", e),
            )
        })?;

        std::fs::write(&self.file_path, contents).map_err(|e| {
            TorshDistributedError::backend_error(
                "FileStore",
                format!("Failed to write store file: {}", e),
            )
        })?;

        Ok(())
    }
}

#[async_trait::async_trait]
impl Store for FileStore {
    async fn set(&self, key: &str, value: &[u8]) -> TorshResult<()> {
        let store_value = StoreValue::new(value.to_vec());
        self.data.write().insert(key.to_string(), store_value);
        self.save_to_file()?;
        Ok(())
    }

    async fn get(&self, key: &str) -> TorshResult<Option<Vec<u8>>> {
        self.load_from_file()?;
        Ok(self.data.read().get(key).map(|v| v.data.clone()))
    }

    async fn wait(&self, keys: &[String]) -> TorshResult<()> {
        let start = Instant::now();

        loop {
            self.load_from_file()?;
            let all_present = {
                let data = self.data.read();
                keys.iter().all(|key| data.contains_key(key))
            }; // RwLockReadGuard is dropped here

            if all_present {
                return Ok(());
            }

            if start.elapsed() > DEFAULT_TIMEOUT {
                return Err(TorshDistributedError::communication_error(
                    "Store wait",
                    "Timeout waiting for keys",
                )
                .into());
            }

            tokio::time::sleep(Duration::from_millis(100)).await;
        }
    }

    async fn delete(&self, key: &str) -> TorshResult<()> {
        self.data.write().remove(key);
        self.save_to_file()?;
        Ok(())
    }

    async fn num_keys(&self) -> TorshResult<usize> {
        self.load_from_file()?;
        Ok(self.data.read().len())
    }

    async fn contains(&self, key: &str) -> TorshResult<bool> {
        self.load_from_file()?;
        Ok(self.data.read().contains_key(key))
    }

    async fn set_with_expiry(&self, key: &str, value: &[u8], _ttl: Duration) -> TorshResult<()> {
        // File store doesn't support TTL, just set normally
        self.set(key, value).await
    }

    async fn compare_and_swap(
        &self,
        key: &str,
        expected: Option<&[u8]>,
        value: &[u8],
    ) -> TorshResult<bool> {
        self.load_from_file()?;
        let mut data = self.data.write();

        match expected {
            Some(expected_val) => {
                if let Some(current) = data.get(key) {
                    if current.data == expected_val {
                        let store_value = StoreValue::new(value.to_vec());
                        data.insert(key.to_string(), store_value);
                        drop(data);
                        self.save_to_file()?;
                        Ok(true)
                    } else {
                        Ok(false)
                    }
                } else {
                    Ok(false)
                }
            }
            None => {
                if data.contains_key(key) {
                    Ok(false)
                } else {
                    let store_value = StoreValue::new(value.to_vec());
                    data.insert(key.to_string(), store_value);
                    drop(data);
                    self.save_to_file()?;
                    Ok(true)
                }
            }
        }
    }

    async fn add(&self, key: &str, value: i64) -> TorshResult<i64> {
        self.load_from_file()?;
        let mut data = self.data.write();

        let new_value = if let Some(existing) = data.get(key) {
            let current = i64::from_le_bytes(existing.data[..8].try_into().map_err(|_| {
                TorshDistributedError::invalid_argument(
                    "value",
                    "Failed to convert stored bytes to i64",
                    "8 bytes representing a valid i64 value",
                )
            })?);
            current + value
        } else {
            value
        };

        let store_value = StoreValue::new(new_value.to_le_bytes().to_vec());
        data.insert(key.to_string(), store_value);
        drop(data);
        self.save_to_file()?;
        Ok(new_value)
    }
}

/// TCP-based distributed store implementation
#[derive(Debug)]
pub struct TcpStore {
    client: Arc<tokio::sync::Mutex<Option<tokio::net::TcpStream>>>,
    master_addr: std::net::IpAddr,
    master_port: u16,
    timeout: Duration,
    data_cache: Arc<DashMap<String, StoreValue>>,
}

impl TcpStore {
    /// Create a new TCP store
    pub fn new(
        master_addr: std::net::IpAddr,
        master_port: u16,
        timeout: Duration,
    ) -> TorshResult<Self> {
        Ok(Self {
            client: Arc::new(tokio::sync::Mutex::new(None)),
            master_addr,
            master_port,
            timeout,
            data_cache: Arc::new(DashMap::new()),
        })
    }

    /// Ensure connection to the master
    async fn ensure_connection(&self) -> TorshResult<()> {
        let mut client = self.client.lock().await;

        if client.is_none() {
            let addr = std::net::SocketAddr::new(self.master_addr, self.master_port);

            match tokio::time::timeout(self.timeout, tokio::net::TcpStream::connect(addr)).await {
                Ok(Ok(stream)) => {
                    *client = Some(stream);
                    info!("🌐 Connected to TCP store at {}", addr);
                }
                Ok(Err(e)) => {
                    return Err(TorshDistributedError::CommunicationError {
                        operation: "TCP connect".to_string(),
                        cause: e.to_string(),
                    }
                    .into());
                }
                Err(_) => {
                    return Err(TorshDistributedError::OperationTimeout {
                        operation: "TCP connect".to_string(),
                        timeout_secs: self.timeout.as_secs(),
                    }
                    .into());
                }
            }
        }

        Ok(())
    }

    /// Send a message to the master and receive response
    async fn send_request(&self, request: TcpStoreMessage) -> TorshResult<TcpStoreResponse> {
        self.ensure_connection().await?;

        let mut client = self.client.lock().await;
        let stream = client.as_mut().expect("client connection should be established");

        // Serialize request
        let request_data = serde_json::to_vec(&request).map_err(|e| {
            TorshDistributedError::serialization_error(format!(
                "Failed to serialize TcpStoreMessage: {}",
                e
            ))
        })?;

        // Send request with length prefix
        let len = request_data.len() as u32;
        tokio::io::AsyncWriteExt::write_all(stream, &len.to_le_bytes())
            .await
            .map_err(|e| TorshDistributedError::CommunicationError {
                operation: "TCP write length".to_string(),
                cause: e.to_string(),
            })?;

        tokio::io::AsyncWriteExt::write_all(stream, &request_data)
            .await
            .map_err(|e| TorshDistributedError::CommunicationError {
                operation: "TCP write data".to_string(),
                cause: e.to_string(),
            })?;

        // Read response length
        let mut len_buf = [0u8; 4];
        tokio::io::AsyncReadExt::read_exact(stream, &mut len_buf)
            .await
            .map_err(|e| TorshDistributedError::CommunicationError {
                operation: "TCP read length".to_string(),
                cause: e.to_string(),
            })?;

        let response_len = u32::from_le_bytes(len_buf) as usize;

        // Read response data
        let mut response_data = vec![0u8; response_len];
        tokio::io::AsyncReadExt::read_exact(stream, &mut response_data)
            .await
            .map_err(|e| TorshDistributedError::CommunicationError {
                operation: "TCP read data".to_string(),
                cause: e.to_string(),
            })?;

        // Deserialize response
        let response: TcpStoreResponse = serde_json::from_slice(&response_data).map_err(|e| {
            TorshDistributedError::SerializationError {
                data_type: "TcpStoreResponse".to_string(),
                cause: e.to_string(),
            }
        })?;

        Ok(response)
    }
}

/// TCP store message types
#[derive(Debug, Clone, Serialize, Deserialize)]
enum TcpStoreMessage {
    Set {
        key: String,
        value: Vec<u8>,
    },
    Get {
        key: String,
    },
    Delete {
        key: String,
    },
    Contains {
        key: String,
    },
    NumKeys,
    Wait {
        keys: Vec<String>,
    },
    CompareAndSwap {
        key: String,
        expected: Option<Vec<u8>>,
        value: Vec<u8>,
    },
    Add {
        key: String,
        value: i64,
    },
}

/// TCP store response types
#[derive(Debug, Clone, Serialize, Deserialize)]
enum TcpStoreResponse {
    Ok,
    Value(Option<Vec<u8>>),
    Bool(bool),
    Number(usize),
    I64(i64),
    Error(String),
}

#[async_trait::async_trait]
impl Store for TcpStore {
    async fn set(&self, key: &str, value: &[u8]) -> TorshResult<()> {
        let message = TcpStoreMessage::Set {
            key: key.to_string(),
            value: value.to_vec(),
        };

        match self.send_request(message).await? {
            TcpStoreResponse::Ok => {
                // Cache the value locally
                self.data_cache
                    .insert(key.to_string(), StoreValue::new(value.to_vec()));
                Ok(())
            }
            TcpStoreResponse::Error(e) => Err(TorshDistributedError::BackendError {
                backend: "TCP store".to_string(),
                message: e,
            }
            .into()),
            _ => Err(TorshDistributedError::BackendError {
                backend: "TCP store".to_string(),
                message: "Unexpected response type for set operation".to_string(),
            }
            .into()),
        }
    }

    async fn get(&self, key: &str) -> TorshResult<Option<Vec<u8>>> {
        // Try cache first
        if let Some(cached) = self.data_cache.get(key) {
            return Ok(Some(cached.data().to_vec()));
        }

        let message = TcpStoreMessage::Get {
            key: key.to_string(),
        };

        match self.send_request(message).await? {
            TcpStoreResponse::Value(value) => {
                // Cache the value if it exists
                if let Some(ref v) = value {
                    self.data_cache
                        .insert(key.to_string(), StoreValue::new(v.clone()));
                }
                Ok(value)
            }
            TcpStoreResponse::Error(e) => Err(TorshDistributedError::BackendError {
                backend: "TCP store".to_string(),
                message: e,
            }
            .into()),
            _ => Err(TorshDistributedError::BackendError {
                backend: "TCP store".to_string(),
                message: "Unexpected response type for get operation".to_string(),
            }
            .into()),
        }
    }

    async fn wait(&self, keys: &[String]) -> TorshResult<()> {
        let message = TcpStoreMessage::Wait {
            keys: keys.to_vec(),
        };

        match self.send_request(message).await? {
            TcpStoreResponse::Ok => Ok(()),
            TcpStoreResponse::Error(e) => Err(TorshDistributedError::BackendError {
                backend: "TCP store".to_string(),
                message: e,
            }
            .into()),
            _ => Err(TorshDistributedError::BackendError {
                backend: "TCP store".to_string(),
                message: "Unexpected response type for wait operation".to_string(),
            }
            .into()),
        }
    }

    async fn delete(&self, key: &str) -> TorshResult<()> {
        let message = TcpStoreMessage::Delete {
            key: key.to_string(),
        };

        match self.send_request(message).await? {
            TcpStoreResponse::Ok => {
                // Remove from cache
                self.data_cache.remove(key);
                Ok(())
            }
            TcpStoreResponse::Error(e) => Err(TorshDistributedError::BackendError {
                backend: "TCP store".to_string(),
                message: e,
            }
            .into()),
            _ => Err(TorshDistributedError::BackendError {
                backend: "TCP store".to_string(),
                message: "Unexpected response type for delete operation".to_string(),
            }
            .into()),
        }
    }

    async fn num_keys(&self) -> TorshResult<usize> {
        let message = TcpStoreMessage::NumKeys;

        match self.send_request(message).await? {
            TcpStoreResponse::Number(count) => Ok(count),
            TcpStoreResponse::Error(e) => Err(TorshDistributedError::BackendError {
                backend: "TCP store".to_string(),
                message: e,
            }
            .into()),
            _ => Err(TorshDistributedError::BackendError {
                backend: "TCP store".to_string(),
                message: "Unexpected response type for num_keys operation".to_string(),
            }
            .into()),
        }
    }

    async fn contains(&self, key: &str) -> TorshResult<bool> {
        // Check cache first
        if self.data_cache.contains_key(key) {
            return Ok(true);
        }

        let message = TcpStoreMessage::Contains {
            key: key.to_string(),
        };

        match self.send_request(message).await? {
            TcpStoreResponse::Bool(exists) => Ok(exists),
            TcpStoreResponse::Error(e) => Err(TorshDistributedError::BackendError {
                backend: "TCP store".to_string(),
                message: e,
            }
            .into()),
            _ => Err(TorshDistributedError::BackendError {
                backend: "TCP store".to_string(),
                message: "Unexpected response type for contains operation".to_string(),
            }
            .into()),
        }
    }

    async fn set_with_expiry(&self, key: &str, value: &[u8], _ttl: Duration) -> TorshResult<()> {
        // For simplicity, TCP store doesn't support TTL - just do regular set
        // In a production implementation, you'd add TTL support to the protocol
        info!("  TCP store doesn't support TTL, using regular set operation");
        self.set(key, value).await
    }

    async fn compare_and_swap(
        &self,
        key: &str,
        expected: Option<&[u8]>,
        value: &[u8],
    ) -> TorshResult<bool> {
        let message = TcpStoreMessage::CompareAndSwap {
            key: key.to_string(),
            expected: expected.map(|v| v.to_vec()),
            value: value.to_vec(),
        };

        match self.send_request(message).await? {
            TcpStoreResponse::Bool(success) => {
                if success {
                    // Update cache
                    self.data_cache
                        .insert(key.to_string(), StoreValue::new(value.to_vec()));
                }
                Ok(success)
            }
            TcpStoreResponse::Error(e) => Err(TorshDistributedError::BackendError {
                backend: "TCP store".to_string(),
                message: e,
            }
            .into()),
            _ => Err(TorshDistributedError::BackendError {
                backend: "TCP store".to_string(),
                message: "Unexpected response type for compare_and_swap operation".to_string(),
            }
            .into()),
        }
    }

    async fn add(&self, key: &str, value: i64) -> TorshResult<i64> {
        let message = TcpStoreMessage::Add {
            key: key.to_string(),
            value,
        };

        match self.send_request(message).await? {
            TcpStoreResponse::I64(new_value) => {
                // Update cache with new value
                self.data_cache.insert(
                    key.to_string(),
                    StoreValue::new(new_value.to_le_bytes().to_vec()),
                );
                Ok(new_value)
            }
            TcpStoreResponse::Error(e) => Err(TorshDistributedError::BackendError {
                backend: "TCP store".to_string(),
                message: e,
            }
            .into()),
            _ => Err(TorshDistributedError::BackendError {
                backend: "TCP store".to_string(),
                message: "Unexpected response type for add operation".to_string(),
            }
            .into()),
        }
    }
}

/// Redis-based distributed store implementation
#[cfg(feature = "redis")]
#[derive(Debug)]
pub struct RedisStore {
    client: RedisClient,
    timeout: Duration,
    data_cache: Arc<DashMap<String, StoreValue>>,
}

#[cfg(feature = "redis")]
impl RedisStore {
    /// Create a new Redis store
    pub async fn new(redis_url: &str, timeout: Duration) -> TorshResult<Self> {
        let client =
            RedisClient::open(redis_url).map_err(|e| TorshDistributedError::BackendError {
                backend: "Redis store".to_string(),
                message: format!("Failed to create Redis client: {}", e),
            })?;

        // Test connection
        let mut conn = client
            .get_multiplexed_async_connection()
            .await
            .map_err(|e| TorshDistributedError::CommunicationError {
                operation: "Redis connect".to_string(),
                cause: e.to_string(),
            })?;

        // Test ping
        let _: String =
            conn.ping()
                .await
                .map_err(|e| TorshDistributedError::CommunicationError {
                    operation: "Redis ping".to_string(),
                    cause: e.to_string(),
                })?;

        info!("🗃️  Connected to Redis store at {}", redis_url);

        Ok(Self {
            client,
            timeout,
            data_cache: Arc::new(DashMap::new()),
        })
    }

    /// Get a connection with timeout
    async fn get_connection(&self) -> TorshResult<redis::aio::MultiplexedConnection> {
        tokio::time::timeout(self.timeout, self.client.get_multiplexed_async_connection())
            .await
            .map_err(|_| TorshDistributedError::OperationTimeout {
                operation: "Redis connection".to_string(),
                timeout_secs: self.timeout.as_secs(),
            })?
            .map_err(|e| TorshDistributedError::CommunicationError {
                operation: "Redis connection".to_string(),
                cause: e.to_string(),
            })
    }
}

#[cfg(feature = "redis")]
#[async_trait::async_trait]
impl Store for RedisStore {
    async fn set(&self, key: &str, value: &[u8]) -> TorshResult<()> {
        let mut conn = self.get_connection().await?;

        tokio::time::timeout(self.timeout, conn.set::<&str, &[u8], ()>(key, value))
            .await
            .map_err(|_| TorshDistributedError::OperationTimeout {
                operation: "Redis set".to_string(),
                timeout_secs: self.timeout.as_secs(),
            })?
            .map_err(|e| TorshDistributedError::BackendError {
                backend: "Redis store".to_string(),
                message: format!("Set operation failed: {}", e),
            })?;

        // Cache the value locally
        self.data_cache
            .insert(key.to_string(), StoreValue::new(value.to_vec()));
        Ok(())
    }

    async fn get(&self, key: &str) -> TorshResult<Option<Vec<u8>>> {
        // Try cache first
        if let Some(cached) = self.data_cache.get(key) {
            return Ok(Some(cached.data().to_vec()));
        }

        let mut conn = self.get_connection().await?;

        let result: Option<Vec<u8>> = tokio::time::timeout(self.timeout, conn.get(key))
            .await
            .map_err(|_| TorshDistributedError::OperationTimeout {
                operation: "Redis get".to_string(),
                timeout_secs: self.timeout.as_secs(),
            })?
            .map_err(|e| TorshDistributedError::BackendError {
                backend: "Redis store".to_string(),
                message: format!("Get operation failed: {}", e),
            })?;

        // Cache the value if it exists
        if let Some(ref v) = result {
            self.data_cache
                .insert(key.to_string(), StoreValue::new(v.clone()));
        }

        Ok(result)
    }

    async fn wait(&self, keys: &[String]) -> TorshResult<()> {
        let mut conn = self.get_connection().await?;
        let start = Instant::now();

        loop {
            let mut all_present = true;

            for key in keys {
                let exists: bool = tokio::time::timeout(self.timeout, conn.exists(key))
                    .await
                    .map_err(|_| TorshDistributedError::OperationTimeout {
                        operation: "Redis exists".to_string(),
                        timeout_secs: self.timeout.as_secs(),
                    })?
                    .map_err(|e| TorshDistributedError::BackendError {
                        backend: "Redis store".to_string(),
                        message: format!("Exists operation failed: {}", e),
                    })?;

                if !exists {
                    all_present = false;
                    break;
                }
            }

            if all_present {
                return Ok(());
            }

            if start.elapsed() > self.timeout {
                return Err(TorshDistributedError::OperationTimeout {
                    operation: "Redis wait".to_string(),
                    timeout_secs: self.timeout.as_secs(),
                }
                .into());
            }

            tokio::time::sleep(Duration::from_millis(100)).await;
        }
    }

    async fn delete(&self, key: &str) -> TorshResult<()> {
        let mut conn = self.get_connection().await?;

        tokio::time::timeout(self.timeout, conn.del::<&str, ()>(key))
            .await
            .map_err(|_| TorshDistributedError::OperationTimeout {
                operation: "Redis delete".to_string(),
                timeout_secs: self.timeout.as_secs(),
            })?
            .map_err(|e| TorshDistributedError::BackendError {
                backend: "Redis store".to_string(),
                message: format!("Delete operation failed: {}", e),
            })?;

        // Remove from cache
        self.data_cache.remove(key);
        Ok(())
    }

    async fn num_keys(&self) -> TorshResult<usize> {
        let mut conn = self.get_connection().await?;

        let count: usize = tokio::time::timeout(self.timeout, conn.dbsize())
            .await
            .map_err(|_| TorshDistributedError::OperationTimeout {
                operation: "Redis dbsize".to_string(),
                timeout_secs: self.timeout.as_secs(),
            })?
            .map_err(|e| TorshDistributedError::BackendError {
                backend: "Redis store".to_string(),
                message: format!("Dbsize operation failed: {}", e),
            })?;

        Ok(count)
    }

    async fn contains(&self, key: &str) -> TorshResult<bool> {
        // Check cache first
        if self.data_cache.contains_key(key) {
            return Ok(true);
        }

        let mut conn = self.get_connection().await?;

        let exists: bool = tokio::time::timeout(self.timeout, conn.exists(key))
            .await
            .map_err(|_| TorshDistributedError::OperationTimeout {
                operation: "Redis exists".to_string(),
                timeout_secs: self.timeout.as_secs(),
            })?
            .map_err(|e| TorshDistributedError::BackendError {
                backend: "Redis store".to_string(),
                message: format!("Exists operation failed: {}", e),
            })?;

        Ok(exists)
    }

    async fn set_with_expiry(&self, key: &str, value: &[u8], ttl: Duration) -> TorshResult<()> {
        let mut conn = self.get_connection().await?;

        tokio::time::timeout(
            self.timeout,
            conn.set_ex::<&str, &[u8], ()>(key, value, ttl.as_secs()),
        )
        .await
        .map_err(|_| TorshDistributedError::OperationTimeout {
            operation: "Redis set_ex".to_string(),
            timeout_secs: self.timeout.as_secs(),
        })?
        .map_err(|e| TorshDistributedError::BackendError {
            backend: "Redis store".to_string(),
            message: format!("Set with expiry operation failed: {}", e),
        })?;

        // Cache the value locally (note: we don't implement TTL in local cache)
        self.data_cache
            .insert(key.to_string(), StoreValue::new(value.to_vec()));
        Ok(())
    }

    async fn compare_and_swap(
        &self,
        key: &str,
        expected: Option<&[u8]>,
        value: &[u8],
    ) -> TorshResult<bool> {
        let mut conn = self.get_connection().await?;

        // Use Redis WATCH/MULTI/EXEC for atomic compare-and-swap
        let mut pipe = redis::pipe();
        pipe.atomic();

        match expected {
            Some(expected_val) => {
                // Watch the key for changes
                tokio::time::timeout(self.timeout, conn.watch(key))
                    .await
                    .map_err(|_| TorshDistributedError::OperationTimeout {
                        operation: "Redis watch".to_string(),
                        timeout_secs: self.timeout.as_secs(),
                    })?
                    .map_err(|e| TorshDistributedError::BackendError {
                        backend: "Redis store".to_string(),
                        message: format!("Watch operation failed: {}", e),
                    })?;

                // Get current value
                let current: Option<Vec<u8>> = tokio::time::timeout(self.timeout, conn.get(key))
                    .await
                    .map_err(|_| TorshDistributedError::OperationTimeout {
                        operation: "Redis get".to_string(),
                        timeout_secs: self.timeout.as_secs(),
                    })?
                    .map_err(|e| TorshDistributedError::BackendError {
                        backend: "Redis store".to_string(),
                        message: format!("Get operation failed: {}", e),
                    })?;

                // Check if current value matches expected
                if current.as_ref().map(|v| v.as_slice()) == Some(expected_val) {
                    pipe.set(key, value);
                    let result: Option<redis::Value> =
                        tokio::time::timeout(self.timeout, pipe.query_async(&mut conn))
                            .await
                            .map_err(|_| TorshDistributedError::OperationTimeout {
                                operation: "Redis transaction".to_string(),
                                timeout_secs: self.timeout.as_secs(),
                            })?
                            .map_err(|e| TorshDistributedError::BackendError {
                                backend: "Redis store".to_string(),
                                message: format!("Transaction failed: {}", e),
                            })?;

                    // Transaction succeeded if result is not nil
                    let success = result.is_some();
                    if success {
                        self.data_cache
                            .insert(key.to_string(), StoreValue::new(value.to_vec()));
                    }
                    Ok(success)
                } else {
                    Ok(false)
                }
            }
            None => {
                // Set only if key doesn't exist (using SET NX)
                let result: bool = tokio::time::timeout(self.timeout, conn.set_nx(key, value))
                    .await
                    .map_err(|_| TorshDistributedError::OperationTimeout {
                        operation: "Redis set_nx".to_string(),
                        timeout_secs: self.timeout.as_secs(),
                    })?
                    .map_err(|e| TorshDistributedError::BackendError {
                        backend: "Redis store".to_string(),
                        message: format!("Set NX operation failed: {}", e),
                    })?;

                if result {
                    self.data_cache
                        .insert(key.to_string(), StoreValue::new(value.to_vec()));
                }
                Ok(result)
            }
        }
    }

    async fn add(&self, key: &str, value: i64) -> TorshResult<i64> {
        let mut conn = self.get_connection().await?;

        let new_value: i64 = tokio::time::timeout(self.timeout, conn.incr(key, value))
            .await
            .map_err(|_| TorshDistributedError::OperationTimeout {
                operation: "Redis incr".to_string(),
                timeout_secs: self.timeout.as_secs(),
            })?
            .map_err(|e| TorshDistributedError::BackendError {
                backend: "Redis store".to_string(),
                message: format!("Increment operation failed: {}", e),
            })?;

        // Update cache with new value
        self.data_cache.insert(
            key.to_string(),
            StoreValue::new(new_value.to_le_bytes().to_vec()),
        );
        Ok(new_value)
    }
}

/// Create a distributed store based on configuration
pub fn create_store(config: &StoreConfig) -> TorshResult<Box<dyn Store>> {
    match config.backend {
        StoreBackend::Memory => Ok(Box::new(MemoryStore::new())),
        StoreBackend::File => {
            let file_path = config.file_path.as_ref().ok_or_else(|| {
                TorshDistributedError::invalid_argument(
                    "file_path",
                    "File path is required when using file store backend",
                    "valid file path string",
                )
            })?;
            Ok(Box::new(FileStore::new(file_path.clone())?))
        }
        StoreBackend::Tcp => {
            let master_addr =
                config
                    .master_addr
                    .ok_or_else(|| TorshDistributedError::InvalidArgument {
                        arg: "master_addr".to_string(),
                        reason: "Master address required for TCP store".to_string(),
                        expected: "Valid IP address".to_string(),
                    })?;
            let master_port =
                config
                    .master_port
                    .ok_or_else(|| TorshDistributedError::InvalidArgument {
                        arg: "master_port".to_string(),
                        reason: "Master port required for TCP store".to_string(),
                        expected: "Valid port number".to_string(),
                    })?;
            Ok(Box::new(TcpStore::new(
                master_addr,
                master_port,
                config.timeout,
            )?))
        }
        StoreBackend::Redis => {
            #[cfg(feature = "redis")]
            {
                let redis_url = config.redis_url.as_ref().ok_or_else(|| {
                    TorshDistributedError::InvalidArgument {
                        arg: "redis_url".to_string(),
                        reason: "Redis URL required for Redis store".to_string(),
                        expected: "Valid Redis URL (e.g., redis://localhost:6379)".to_string(),
                    }
                })?;

                // Note: RedisStore::new is async, but create_store is sync
                // In a real implementation, you might want to make create_store async
                // For now, we'll return an error indicating async initialization is needed
                Err(TorshDistributedError::FeatureNotAvailable(
                    "Redis store requires async initialization. Use RedisStore::new() directly."
                        .to_string(),
                )
                .into())
            }

            #[cfg(not(feature = "redis"))]
            {
                Err(TorshDistributedError::FeatureNotAvailable(
                    "Redis store feature not enabled. Enable with --features redis".to_string(),
                )
                .into())
            }
        }
    }
}

/// Utility functions for common store operations
impl dyn Store {
    /// Set a string value
    pub async fn set_string(&self, key: &str, value: &str) -> TorshResult<()> {
        self.set(key, value.as_bytes()).await
    }

    /// Get a string value
    pub async fn get_string(&self, key: &str) -> TorshResult<Option<String>> {
        match self.get(key).await? {
            Some(bytes) => {
                let s = String::from_utf8(bytes).map_err(|_| {
                    TorshDistributedError::invalid_argument(
                        "bytes",
                        "Failed to convert bytes to UTF-8 string",
                        "valid UTF-8 encoded bytes",
                    )
                })?;
                Ok(Some(s))
            }
            None => Ok(None),
        }
    }

    /// Set an integer value
    pub async fn set_i64(&self, key: &str, value: i64) -> TorshResult<()> {
        self.set(key, &value.to_le_bytes()).await
    }

    /// Get an integer value
    pub async fn get_i64(&self, key: &str) -> TorshResult<Option<i64>> {
        match self.get(key).await? {
            Some(bytes) => {
                if bytes.len() == 8 {
                    let array: [u8; 8] = bytes.try_into().map_err(|_| {
                        TorshDistributedError::invalid_argument(
                            "bytes",
                            "Failed to convert bytes to 8-byte array for i64",
                            "exactly 8 bytes",
                        )
                    })?;
                    Ok(Some(i64::from_le_bytes(array)))
                } else {
                    Err(TorshDistributedError::invalid_argument(
                        "bytes",
                        format!("Invalid byte length for i64: got {} bytes", bytes.len()),
                        "exactly 8 bytes",
                    )
                    .into())
                }
            }
            None => Ok(None),
        }
    }
}

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

    #[tokio::test]
    async fn test_memory_store() -> TorshResult<()> {
        let store = MemoryStore::new();

        // Test basic set/get
        store.set("key1", b"value1").await?;
        let value = store.get("key1").await?;
        assert_eq!(value, Some(b"value1".to_vec()));

        // Test non-existent key
        let value = store.get("nonexistent").await?;
        assert_eq!(value, None);

        // Test contains
        assert!(store.contains("key1").await?);
        assert!(!store.contains("nonexistent").await?);

        // Test delete
        store.delete("key1").await?;
        assert!(!store.contains("key1").await?);

        // Test wait
        tokio::spawn({
            let store = MemoryStore::new();
            async move {
                tokio::time::sleep(Duration::from_millis(50)).await;
                store.set("async_key", b"async_value").await.unwrap();
            }
        });

        // This should complete when the key is set
        let store2 = MemoryStore::new();
        store2.set("async_key", b"async_value").await?;
        store2.wait(&["async_key".to_string()]).await?;

        Ok(())
    }

    #[tokio::test]
    async fn test_file_store() -> TorshResult<()> {
        let temp_dir = tempdir().unwrap();
        let file_path = temp_dir
            .path()
            .join("test_store.json")
            .to_string_lossy()
            .to_string();

        let store = FileStore::new(file_path)?;

        // Test basic set/get
        store.set("key1", b"value1").await?;
        let value = store.get("key1").await?;
        assert_eq!(value, Some(b"value1".to_vec()));

        // Test persistence by creating a new store instance
        let store2 = FileStore::new(
            temp_dir
                .path()
                .join("test_store.json")
                .to_string_lossy()
                .to_string(),
        )?;
        let value = store2.get("key1").await?;
        assert_eq!(value, Some(b"value1".to_vec()));

        Ok(())
    }

    #[tokio::test]
    async fn test_store_utility_functions() -> TorshResult<()> {
        let store: Box<dyn Store> = Box::new(MemoryStore::new());

        // Test string functions
        store.set_string("str_key", "hello world").await?;
        let value = store.get_string("str_key").await?;
        assert_eq!(value, Some("hello world".to_string()));

        // Test i64 functions
        store.set_i64("int_key", 42).await?;
        let value = store.get_i64("int_key").await?;
        assert_eq!(value, Some(42));

        // Test add function
        let result = store.add("counter", 10).await?;
        assert_eq!(result, 10);
        let result = store.add("counter", 5).await?;
        assert_eq!(result, 15);

        Ok(())
    }

    #[cfg(feature = "redis")]
    #[tokio::test]
    async fn test_redis_store() -> TorshResult<()> {
        // Note: This test requires a Redis instance running at redis://localhost:6379
        // Skip if Redis is not available
        let redis_url = "redis://localhost:6379";

        let store = match RedisStore::new(redis_url, Duration::from_secs(5)).await {
            Ok(store) => store,
            Err(_) => {
                info!(
                    "  Skipping Redis test - Redis not available at {}",
                    redis_url
                );
                return Ok(());
            }
        };

        // Test basic set/get
        store.set("redis_key1", b"redis_value1").await?;
        let value = store.get("redis_key1").await?;
        assert_eq!(value, Some(b"redis_value1".to_vec()));

        // Test non-existent key
        let value = store.get("nonexistent_redis").await?;
        assert_eq!(value, None);

        // Test contains
        assert!(store.contains("redis_key1").await?);
        assert!(!store.contains("nonexistent_redis").await?);

        // Test delete
        store.delete("redis_key1").await?;
        assert!(!store.contains("redis_key1").await?);

        // Test set with expiry
        store
            .set_with_expiry("expiry_key", b"expiry_value", Duration::from_secs(1))
            .await?;
        assert!(store.contains("expiry_key").await?);

        // Wait for expiry (this would require waiting, but we'll skip for the test)
        // tokio::time::sleep(Duration::from_secs(2)).await;
        // assert!(!store.contains("expiry_key").await?);

        // Test compare and swap
        store.set("cas_key", b"initial").await?;
        let success = store
            .compare_and_swap("cas_key", Some(b"initial"), b"updated")
            .await?;
        assert!(success);
        let value = store.get("cas_key").await?;
        assert_eq!(value, Some(b"updated".to_vec()));

        // Test failed compare and swap
        let success = store
            .compare_and_swap("cas_key", Some(b"wrong"), b"failed")
            .await?;
        assert!(!success);

        // Test add operation
        let result = store.add("redis_counter", 10).await?;
        assert_eq!(result, 10);
        let result = store.add("redis_counter", 5).await?;
        assert_eq!(result, 15);

        // Clean up
        store.delete("cas_key").await?;
        store.delete("expiry_key").await?;
        store.delete("redis_counter").await?;

        Ok(())
    }

    #[tokio::test]
    async fn test_store_creation() -> TorshResult<()> {
        // Test memory store creation
        let config = StoreConfig {
            backend: StoreBackend::Memory,
            ..Default::default()
        };
        let _store = create_store(&config)?;

        // Test file store creation
        let temp_dir = tempfile::tempdir().unwrap();
        let file_path = temp_dir
            .path()
            .join("test.json")
            .to_string_lossy()
            .to_string();
        let config = StoreConfig {
            backend: StoreBackend::File,
            file_path: Some(file_path),
            ..Default::default()
        };
        let _store = create_store(&config)?;

        // Test TCP store creation
        let config = StoreConfig {
            backend: StoreBackend::Tcp,
            master_addr: Some("127.0.0.1".parse().unwrap()),
            master_port: Some(29500),
            ..Default::default()
        };
        let _store = create_store(&config)?;

        // Test Redis store configuration validation
        let config = StoreConfig {
            backend: StoreBackend::Redis,
            redis_url: Some("redis://localhost:6379".to_string()),
            ..Default::default()
        };
        let result = create_store(&config);
        assert!(result.is_err()); // Should fail because we need async initialization

        Ok(())
    }
}