remdb 0.3.1

嵌入式内存数据库
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
#[cfg(feature = "ha")]
use remdb::config::HAConfig;
use remdb::config::{
    DbConfig, DefaultMemoryAllocator, LogMode, TimeSeriesConfig, WALCompressionType, WALConfig,
};
#[cfg(feature = "ha")]
use remdb::ha::{HARole, ReplicationMode};
use remdb::platform::{init_platform, FileHandle, FileMode, FileResult, Platform, SeekWhence};
use remdb::transaction::{LogItem, LogManager, LogOperation, VariableSizeLogItem};
use serial_test::serial;

mod common;
use common::{setup_test_db, setup_test_db_with_posix};

#[cfg(windows)]
fn get_test_wal_path(name: &str) -> &'static str {
    let s = format!("C:\\temp\\{}", name);
    Box::leak(s.into_boxed_str())
}

#[cfg(not(windows))]
fn get_test_wal_path(name: &str) -> &'static str {
    let s = format!("/tmp/{}", name);
    Box::leak(s.into_boxed_str())
}

// 测试 WAL 功能的测试用例
#[test]
#[serial]
fn test_wal_log_manager_creation() {
    setup_test_db_with_posix();

    // 创建内存分配器
    static ALLOCATOR: DefaultMemoryAllocator = DefaultMemoryAllocator;

    // 创建数据库配置
    let config = DbConfig {
        tables: vec![],
        total_memory: 1024 * 1024, // 1MB
        low_power_mode_supported: false,
        low_power_max_records: None,
        default_max_records: 1000,
        memory_allocator: &ALLOCATOR,
        wal_config: WALConfig {
            log_path: &get_test_wal_path("test_wal.log"),
            log_mode: LogMode::Sync,
            checkpoint_interval_ms: 60000,
            log_file_size_limit: 16 * 1024 * 1024,
            log_prealloc_size: 1 * 1024 * 1024,
            log_segment_size: 16 * 1024 * 1024,
            retained_checkpoints: 3,
            max_consecutive_invalid: 100,
            skip_threshold: 1000,
            skip_block_size: 1024 * 1024,
            max_skip_attempts: 3,
            compression_type: WALCompressionType::None,
            compression_level: 3,
        },
        time_series_defaults: TimeSeriesConfig::DEFAULT,
        #[cfg(feature = "pubsub")]
        pubsub_config: None,
        #[cfg(feature = "ha")]
        ha_config: Some(HAConfig {
            node_id: 1, // 默认节点ID为1
            ha_role: HARole::Auto,
            replication_mode: ReplicationMode::Async,
            heartbeat_interval_ms: 1000,
            failure_detection_ms: 3000,
            sync_timeout_ms: 2000,
            master_address: None,
            master_port: None,
            replication_port: 5556,
        }),

        model_worker_config: Default::default(),
    };

    // 测试创建 LogManager
    unsafe {
        let log_path = &get_test_wal_path("test_wal.log");
        let log_manager = LogManager::new(&config);
        assert!(log_manager.is_ok());
    }
}

#[test]
#[serial]
fn test_wal_log_write_sync_mode() {
    setup_test_db_with_posix();

    // 创建内存分配器
    static ALLOCATOR: DefaultMemoryAllocator = DefaultMemoryAllocator;

    // 创建同步模式的数据库配置
    let config = DbConfig {
        tables: vec![],
        total_memory: 1024 * 1024, // 1MB
        low_power_mode_supported: false,
        low_power_max_records: None,
        default_max_records: 1000,
        memory_allocator: &ALLOCATOR,
        wal_config: WALConfig {
            log_path: &get_test_wal_path("test_wal_sync.log"),
            log_mode: LogMode::Sync,
            checkpoint_interval_ms: 60000,
            log_file_size_limit: 16 * 1024 * 1024,
            log_prealloc_size: 1 * 1024 * 1024,
            log_segment_size: 16 * 1024 * 1024,
            retained_checkpoints: 3,
            max_consecutive_invalid: 100,
            skip_threshold: 1000,
            skip_block_size: 1024 * 1024,
            max_skip_attempts: 3,
            compression_type: WALCompressionType::None,
            compression_level: 3,
        },
        time_series_defaults: TimeSeriesConfig::DEFAULT,
        #[cfg(feature = "pubsub")]
        pubsub_config: None,
        #[cfg(feature = "ha")]
        ha_config: Some(HAConfig {
            node_id: 1, // 默认节点ID为1
            ha_role: HARole::Auto,
            replication_mode: ReplicationMode::Async,
            heartbeat_interval_ms: 1000,
            failure_detection_ms: 3000,
            sync_timeout_ms: 2000,
            master_address: None,
            master_port: None,
            replication_port: 5556,
        }),

        model_worker_config: Default::default(),
    };

    unsafe {
        let log_path = &get_test_wal_path("test_wal_sync.log");
        let mut log_manager = LogManager::new(&config).unwrap();

        let mut new_data = [0u8; 512];
        new_data[0..8].copy_from_slice(&[0, 1, 2, 3, 4, 5, 6, 7]);

        let var_log_item = VariableSizeLogItem {
            header: LogItem {
                op_type: LogOperation::Insert,
                table_id: 0,
                record_id: 1,
                old_data_size: 0,
                new_data_size: 8,
                tx_id: 1,
                timestamp: 1234567890,
                checksum: 0,
            },
            old_data: Vec::new(),
            new_data: new_data[0..8].to_vec(),
        };

        let result = log_manager.write_variable_size_log_item(&var_log_item);
        assert!(result.is_ok());
    }
}

#[test]
#[serial]
fn test_wal_log_write_async_mode() {
    setup_test_db_with_posix();

    // 创建内存分配器
    static ALLOCATOR: DefaultMemoryAllocator = DefaultMemoryAllocator;

    // 创建异步模式的数据库配置
    let config = DbConfig {
        tables: vec![],
        total_memory: 1024 * 1024, // 1MB
        low_power_mode_supported: false,
        low_power_max_records: None,
        default_max_records: 1000,
        memory_allocator: &ALLOCATOR,
        wal_config: WALConfig {
            log_path: &get_test_wal_path("test_wal_async.log"),
            log_mode: LogMode::Async,
            checkpoint_interval_ms: 60000,
            log_file_size_limit: 16 * 1024 * 1024,
            log_prealloc_size: 1 * 1024 * 1024,
            log_segment_size: 16 * 1024 * 1024,
            retained_checkpoints: 3,
            max_consecutive_invalid: 100,
            skip_threshold: 1000,
            skip_block_size: 1024 * 1024,
            max_skip_attempts: 3,
            compression_type: WALCompressionType::None,
            compression_level: 3,
        },
        time_series_defaults: TimeSeriesConfig::DEFAULT,
        #[cfg(feature = "pubsub")]
        pubsub_config: None,
        #[cfg(feature = "ha")]
        ha_config: Some(HAConfig {
            node_id: 1, // 默认节点ID为1
            ha_role: HARole::Auto,
            replication_mode: ReplicationMode::Async,
            heartbeat_interval_ms: 1000,
            failure_detection_ms: 3000,
            sync_timeout_ms: 2000,
            master_address: None,
            master_port: None,
            replication_port: 5556,
        }),

        model_worker_config: Default::default(),
    };

    unsafe {
        let log_path = &get_test_wal_path("test_wal_async.log");
        let mut log_manager = LogManager::new(&config).unwrap();

        let old_data: [u8; 8] = [0, 1, 2, 3, 4, 5, 6, 7];
        let new_data: [u8; 8] = [7, 6, 5, 4, 3, 2, 1, 0];

        let var_log_item = VariableSizeLogItem {
            header: LogItem {
                op_type: LogOperation::Update,
                table_id: 0,
                record_id: 1,
                old_data_size: 8,
                new_data_size: 8,
                tx_id: 1,
                timestamp: 1234567890,
                checksum: 0,
            },
            old_data: old_data.to_vec(),
            new_data: new_data.to_vec(),
        };

        let result = log_manager.write_variable_size_log_item(&var_log_item);
        assert!(result.is_ok());

        let result = log_manager.flush_buffer();
        assert!(result.is_ok());
    }
}

#[test]
#[serial]
fn test_wal_checkpoint_mechanism() {
    setup_test_db_with_posix();

    // 创建内存分配器
    static ALLOCATOR: DefaultMemoryAllocator = DefaultMemoryAllocator;

    // 创建数据库配置,使用短检查点间隔
    let config = DbConfig {
        tables: vec![],
        total_memory: 1024 * 1024, // 1MB
        low_power_mode_supported: false,
        low_power_max_records: None,
        default_max_records: 1000,
        memory_allocator: &ALLOCATOR,
        wal_config: WALConfig {
            log_path: &get_test_wal_path("test_wal_checkpoint.log"),
            log_mode: LogMode::Sync,
            checkpoint_interval_ms: 100, // 100毫秒检查点间隔
            log_file_size_limit: 16 * 1024 * 1024,
            log_prealloc_size: 1 * 1024 * 1024,
            log_segment_size: 16 * 1024 * 1024,
            retained_checkpoints: 3,
            max_consecutive_invalid: 100,
            skip_threshold: 1000,
            skip_block_size: 1024 * 1024,
            max_skip_attempts: 3,
            compression_type: WALCompressionType::None,
            compression_level: 3,
        },
        time_series_defaults: TimeSeriesConfig::DEFAULT,
        #[cfg(feature = "pubsub")]
        pubsub_config: None,
        #[cfg(feature = "ha")]
        ha_config: Some(HAConfig {
            node_id: 1, // 默认节点ID为1
            ha_role: HARole::Auto,
            replication_mode: ReplicationMode::Async,
            heartbeat_interval_ms: 1000,
            failure_detection_ms: 3000,
            sync_timeout_ms: 2000,
            master_address: None,
            master_port: None,
            replication_port: 5556,
        }),

        model_worker_config: Default::default(),
    };

    unsafe {
        let log_path = &get_test_wal_path("test_wal_checkpoint.log");
        let mut log_manager = LogManager::new(&config).unwrap();

        // 模拟检查点触发
        let result = log_manager.check_flush_and_checkpoint();
        assert!(result.is_ok());

        // 写入一些日志项
        for i in 0..5 {
            let log_item = LogItem {
                op_type: LogOperation::Insert,
                table_id: 0,
                record_id: i as u16,
                old_data_size: 8,
                new_data_size: 8,
                tx_id: 1,
                timestamp: 1234567890u64 + i as u64,
                checksum: 0,
            };

            log_manager.write_log_item(&log_item).unwrap();
        }

        // 再次检查检查点
        let result = log_manager.check_flush_and_checkpoint();
        assert!(result.is_ok());
    }
}

#[test]
#[serial]
fn test_wal_log_preallocation() {
    setup_test_db_with_posix();

    // 创建内存分配器
    static ALLOCATOR: DefaultMemoryAllocator = DefaultMemoryAllocator;

    // 创建带有大预分配大小的配置
    let config = DbConfig {
        tables: vec![],
        total_memory: 1024 * 1024, // 1MB
        low_power_mode_supported: false,
        low_power_max_records: None,
        default_max_records: 1000,
        memory_allocator: &ALLOCATOR,
        wal_config: WALConfig {
            log_path: &get_test_wal_path("test_wal_prealloc.log"),
            log_mode: LogMode::Sync,
            checkpoint_interval_ms: 60000,
            log_file_size_limit: 16 * 1024 * 1024,
            log_prealloc_size: 32 * 1024 * 1024, // 32MB 预分配大小
            log_segment_size: 16 * 1024 * 1024,
            retained_checkpoints: 3,
            max_consecutive_invalid: 100,
            skip_threshold: 1000,
            skip_block_size: 1024 * 1024,
            max_skip_attempts: 3,
            compression_type: WALCompressionType::None,
            compression_level: 3,
        },
        time_series_defaults: TimeSeriesConfig::DEFAULT,
        #[cfg(feature = "pubsub")]
        pubsub_config: None,
        #[cfg(feature = "ha")]
        ha_config: Some(HAConfig {
            node_id: 1, // 默认节点ID为1
            ha_role: HARole::Auto,
            replication_mode: ReplicationMode::Async,
            heartbeat_interval_ms: 1000,
            failure_detection_ms: 3000,
            sync_timeout_ms: 2000,
            master_address: None,
            master_port: None,
            replication_port: 5556,
        }),

        model_worker_config: Default::default(),
    };

    unsafe {
        let log_path = &get_test_wal_path("test_wal_prealloc.log");
        let log_manager = LogManager::new(&config);
        assert!(log_manager.is_ok());

        // 这里可以添加文件大小检查,但需要平台特定的API
        // 暂时只测试创建成功
    }
}

#[test]
#[serial]
fn test_wal_different_log_modes() {
    setup_test_db_with_posix();

    // 测试不同日志模式的行为差异
    // 使用静态字符串作为日志路径
    static LOG_PATH_SYNC: &str = "test_wal_mode_sync.log";
    static LOG_PATH_ASYNC: &str = "test_wal_mode_async.log";

    let modes = [
        (LogMode::Sync, &get_test_wal_path(LOG_PATH_SYNC) as &str),
        (LogMode::Async, &get_test_wal_path(LOG_PATH_ASYNC) as &str),
    ];

    for (mode, log_path) in modes {
        // 创建内存分配器
        static ALLOCATOR: DefaultMemoryAllocator = DefaultMemoryAllocator;

        let config = DbConfig {
            tables: vec![],
            total_memory: 1024 * 1024, // 1MB
            low_power_mode_supported: false,
            low_power_max_records: None,
            default_max_records: 1000,
            memory_allocator: &ALLOCATOR,
            wal_config: WALConfig {
                log_path,
                log_mode: mode,
                checkpoint_interval_ms: 60000,
                log_file_size_limit: 16 * 1024 * 1024,
                log_prealloc_size: 1 * 1024 * 1024,
                log_segment_size: 16 * 1024 * 1024,
                retained_checkpoints: 3,
                max_consecutive_invalid: 100,
                skip_threshold: 1000,
                skip_block_size: 1024 * 1024,
                max_skip_attempts: 3,
                compression_type: WALCompressionType::None,
                compression_level: 3,
            },
            time_series_defaults: TimeSeriesConfig::DEFAULT,
            #[cfg(feature = "pubsub")]
            pubsub_config: None,
            #[cfg(feature = "ha")]
            ha_config: Some(HAConfig {
                node_id: 1, // 默认节点ID为1
                ha_role: HARole::Auto,
                replication_mode: ReplicationMode::Async,
                heartbeat_interval_ms: 1000,
                failure_detection_ms: 3000,
                sync_timeout_ms: 2000,
                master_address: None,
                master_port: None,
                replication_port: 5556,
            }),

            model_worker_config: Default::default(),
        };

        unsafe {
            let mut log_manager = LogManager::new(&config).unwrap();

            let mut new_data = [0u8; 512];
            new_data[0..8].copy_from_slice(&[1, 2, 3, 4, 5, 6, 7, 8]);

            let var_log_item = VariableSizeLogItem {
                header: LogItem {
                    op_type: LogOperation::Insert,
                    table_id: 0,
                    record_id: 1,
                    old_data_size: 0,
                    new_data_size: 8,
                    tx_id: 1,
                    timestamp: 1234567890,
                    checksum: 0,
                },
                old_data: Vec::new(),
                new_data: new_data[0..8].to_vec(),
            };

            let result = log_manager.write_variable_size_log_item(&var_log_item);
            assert!(result.is_ok());

            if mode == LogMode::Async {
                let result = log_manager.flush_buffer();
                assert!(result.is_ok());
            }
        }
    }
}

#[test]
#[serial]
fn test_wal_checkpoint_comprehensive() {
    setup_test_db_with_posix();

    // 创建内存分配器
    static ALLOCATOR: DefaultMemoryAllocator = DefaultMemoryAllocator;

    // 创建数据库配置,使用短检查点间隔和有限的保留数量
    let config = DbConfig {
        tables: vec![],
        total_memory: 1024 * 1024, // 1MB
        low_power_mode_supported: false,
        low_power_max_records: None,
        default_max_records: 1000,
        memory_allocator: &ALLOCATOR,
        wal_config: WALConfig {
            log_path: &get_test_wal_path("test_wal_checkpoint_comprehensive.log"),
            log_mode: LogMode::Sync,
            checkpoint_interval_ms: 50, // 50毫秒检查点间隔,便于测试
            log_file_size_limit: 16 * 1024 * 1024,
            log_prealloc_size: 1 * 1024 * 1024,
            log_segment_size: 16 * 1024 * 1024,
            retained_checkpoints: 2, // 只保留2个检查点
            max_consecutive_invalid: 100,
            skip_threshold: 1000,
            skip_block_size: 1024 * 1024,
            max_skip_attempts: 3,
            compression_type: WALCompressionType::None,
            compression_level: 3,
        },
        time_series_defaults: TimeSeriesConfig::DEFAULT,
        #[cfg(feature = "pubsub")]
        pubsub_config: None,
        #[cfg(feature = "ha")]
        ha_config: Some(HAConfig {
            node_id: 1, // 默认节点ID为1
            ha_role: HARole::Auto,
            replication_mode: ReplicationMode::Async,
            heartbeat_interval_ms: 1000,
            failure_detection_ms: 3000,
            sync_timeout_ms: 2000,
            master_address: None,
            master_port: None,
            replication_port: 5556,
        }),

        model_worker_config: Default::default(),
    };

    unsafe {
        println!("=== 开始全面Checkpoint测试 ===");

        // 步骤1: 创建日志管理器
        let mut log_manager = LogManager::new(&config).unwrap();
        println!("1. 日志管理器创建成功");

        // 步骤2: 写入一批日志并触发多次checkpoint
        println!("\n2. 写入测试数据并触发checkpoint...");

        // 写入第一组日志并触发checkpoint
        for i in 0..3 {
            let log_item = LogItem {
                op_type: LogOperation::Insert,
                table_id: 0,
                record_id: i as u16,
                old_data_size: 8,
                new_data_size: 8,
                tx_id: 1,
                timestamp: 1234567890u64 + i as u64,
                checksum: 0,
            };

            log_manager.write_log_item(&log_item).unwrap();
        }

        // 手动触发第一个checkpoint
        log_manager.check_flush_and_checkpoint().unwrap();
        println!("   ✅ 第一个checkpoint触发成功");

        // 写入第二组日志
        for i in 3..6 {
            let log_item = LogItem {
                op_type: LogOperation::Insert,
                table_id: 0,
                record_id: i as u16,
                old_data_size: 8,
                new_data_size: 8,
                tx_id: 2,
                timestamp: 1234567900 + i,
                checksum: 0,
            };

            log_manager.write_log_item(&log_item).unwrap();
        }

        // 手动触发第二个checkpoint
        log_manager.check_flush_and_checkpoint().unwrap();
        println!("   ✅ 第二个checkpoint触发成功");

        // 写入第三组日志
        for i in 6..9 {
            let log_item = LogItem {
                op_type: LogOperation::Insert,
                table_id: 0,
                record_id: i as u16,
                old_data_size: 8,
                new_data_size: 8,
                tx_id: 3,
                timestamp: 1234567910u64 + i as u64,
                checksum: 0,
            };

            log_manager.write_log_item(&log_item).unwrap();
        }

        // 手动触发第三个checkpoint,这应该会导致第一个checkpoint被清理
        log_manager.check_flush_and_checkpoint().unwrap();
        println!("   ✅ 第三个checkpoint触发成功(应该清理第一个checkpoint)");

        // 步骤3: 测试checkpoint与恢复的交互
        println!("\n3. 测试checkpoint与恢复的交互...");

        // 写入一些未提交的事务日志
        let update_log = LogItem {
            op_type: LogOperation::Update,
            table_id: 0,
            record_id: 1,
            old_data_size: 8,
            new_data_size: 8,
            tx_id: 4,
            timestamp: 1234567920,
            checksum: 0,
        };

        log_manager.write_log_item(&update_log).unwrap();
        println!("   ✅ 写入未提交事务日志");

        // 模拟系统崩溃
        drop(log_manager);
        println!("   ✅ 模拟系统崩溃");

        // 从崩溃中恢复
        let mut recovered_log_manager = LogManager::new(&config).unwrap();
        println!("   ✅ 从崩溃中恢复成功");

        // 步骤4: 验证恢复后可以继续正常操作
        println!("\n4. 验证恢复后操作...");

        // 写入新的日志项
        let new_log = LogItem {
            op_type: LogOperation::Insert,
            table_id: 0,
            record_id: 10,
            old_data_size: 8,
            new_data_size: 8,
            tx_id: 5,
            timestamp: 1234567930,
            checksum: 0,
        };

        let result = recovered_log_manager.write_log_item(&new_log);
        assert!(result.is_ok(), "恢复后无法写入新日志");
        println!("   ✅ 恢复后写入新日志成功");

        // 再次触发checkpoint
        let result = recovered_log_manager.check_flush_and_checkpoint();
        assert!(result.is_ok(), "恢复后无法触发checkpoint");
        println!("   ✅ 恢复后触发checkpoint成功");

        // 步骤5: 测试不同日志模式下的checkpoint
        println!("\n5. 测试不同日志模式下的checkpoint...");

        // 创建异步模式的配置
        let async_config = DbConfig {
            tables: vec![],
            total_memory: 1024 * 1024,
            low_power_mode_supported: false,
            low_power_max_records: None,
            default_max_records: 1000,
            memory_allocator: &ALLOCATOR,
            wal_config: WALConfig {
                log_path: &get_test_wal_path("test_wal_checkpoint_async.log"),
                log_mode: LogMode::Async,
                checkpoint_interval_ms: 50,
                log_file_size_limit: 16 * 1024 * 1024,
                log_prealloc_size: 1 * 1024 * 1024,
                log_segment_size: 16 * 1024 * 1024,
                retained_checkpoints: 2,
                max_consecutive_invalid: 100,
                skip_threshold: 1000,
                skip_block_size: 1024 * 1024,
                max_skip_attempts: 3,
                compression_type: WALCompressionType::None,
                compression_level: 3,
            },
            time_series_defaults: TimeSeriesConfig::DEFAULT,
            #[cfg(feature = "pubsub")]
            pubsub_config: None,
            #[cfg(feature = "ha")]
            ha_config: Some(HAConfig {
                node_id: 1,
                ha_role: HARole::Auto,
                replication_mode: ReplicationMode::Async,
                heartbeat_interval_ms: 1000,
                failure_detection_ms: 3000,
                sync_timeout_ms: 2000,
                master_address: None,
                master_port: None,
                replication_port: 5556,
            }),

            model_worker_config: Default::default(),
        };

        let mut async_log_manager = LogManager::new(&async_config).unwrap();

        // 写入日志并触发checkpoint
        for i in 0..3 {
            let log_item = LogItem {
                op_type: LogOperation::Insert,
                table_id: 0,
                record_id: i as u16,
                old_data_size: 0,
                new_data_size: 4,
                tx_id: 1,
                timestamp: 1234567890 + i,
                checksum: 0,
            };

            async_log_manager.write_log_item(&log_item).unwrap();
        }

        // 手动刷新缓冲区并触发checkpoint
        async_log_manager.flush_buffer().unwrap();
        let result = async_log_manager.check_flush_and_checkpoint();
        assert!(result.is_ok(), "异步模式下无法触发checkpoint");
        println!("   ✅ 异步模式下checkpoint成功");

        drop(async_log_manager);

        println!("\n=== 全面Checkpoint测试完成! ===");
    }
}

#[test]
#[serial]
fn test_wal_recovery_flow() {
    setup_test_db_with_posix();

    // 创建内存分配器
    static ALLOCATOR: DefaultMemoryAllocator = DefaultMemoryAllocator;

    // 创建数据库配置(简化版,不包含tables字段)
    let config = DbConfig {
        tables: vec![],
        total_memory: 1024 * 1024, // 1MB
        low_power_mode_supported: false,
        low_power_max_records: None,
        default_max_records: 1000,
        memory_allocator: &ALLOCATOR,
        wal_config: WALConfig {
            log_path: &get_test_wal_path("test_wal_recovery.log"),
            log_mode: LogMode::Sync,
            checkpoint_interval_ms: 60000,
            log_file_size_limit: 16 * 1024 * 1024,
            log_prealloc_size: 1 * 1024 * 1024,
            log_segment_size: 16 * 1024 * 1024,
            retained_checkpoints: 3,
            max_consecutive_invalid: 100,
            skip_threshold: 1000,
            skip_block_size: 1024 * 1024,
            max_skip_attempts: 3,
            compression_type: WALCompressionType::None,
            compression_level: 3,
        },
        time_series_defaults: TimeSeriesConfig::DEFAULT,
        #[cfg(feature = "pubsub")]
        pubsub_config: None,
        #[cfg(feature = "ha")]
        ha_config: Some(HAConfig {
            node_id: 1, // 默认节点ID为1
            ha_role: HARole::Auto,
            replication_mode: ReplicationMode::Async,
            heartbeat_interval_ms: 1000,
            failure_detection_ms: 3000,
            sync_timeout_ms: 2000,
            master_address: None,
            master_port: None,
            replication_port: 5556,
        }),

        model_worker_config: Default::default(),
    };

    unsafe {
        let log_path = &get_test_wal_path("test_wal_recovery.log");

        // 步骤1: 创建日志管理器
        let mut log_manager = LogManager::new(&config).unwrap();

        println!("=== WAL恢复流程测试开始 ===");

        // 步骤2: 写入初始数据日志
        println!("=== 写入初始数据日志 ===");

        // 写入第一条日志(插入操作)
        let log_item1 = LogItem {
            op_type: LogOperation::Insert,
            table_id: 0,
            record_id: 1,
            old_data_size: 0,
            new_data_size: 8,
            tx_id: 1,
            timestamp: 1234567890,
            checksum: 0,
        };

        log_manager.write_log_item(&log_item1).unwrap();
        println!("写入日志1: 插入记录 id=1, value=100");

        // 写入第二条日志(插入操作)
        let log_item2 = LogItem {
            op_type: LogOperation::Insert,
            table_id: 0,
            record_id: 2,
            old_data_size: 0,
            new_data_size: 8,
            tx_id: 1,
            timestamp: 1234567891,
            checksum: 0,
        };

        log_manager.write_log_item(&log_item2).unwrap();
        println!("写入日志2: 插入记录 id=2, value=200");

        // 步骤3: 创建检查点
        println!("=== 创建检查点 ===");
        let checkpoint_log = LogItem {
            op_type: LogOperation::Checkpoint,
            table_id: 0,
            record_id: 0,
            old_data_size: 0,
            new_data_size: 0,
            tx_id: 0,
            timestamp: 1234567900,
            checksum: 0,
        };

        log_manager.write_log_item(&checkpoint_log).unwrap();
        println!("创建检查点成功");

        // 步骤4: 写入检查点后的日志
        println!("=== 写入检查点后的数据日志 ===");

        // 更新操作日志
        let update_log = LogItem {
            op_type: LogOperation::Update,
            table_id: 0,
            record_id: 1,
            old_data_size: 8,
            new_data_size: 8,
            tx_id: 2,
            timestamp: 1234567910,
            checksum: 0,
        };

        log_manager.write_log_item(&update_log).unwrap();
        println!("写入日志3: 更新记录 id=1, value=150");

        // 新插入操作日志
        let insert_log = LogItem {
            op_type: LogOperation::Insert,
            table_id: 0,
            record_id: 3,
            old_data_size: 0,
            new_data_size: 8,
            tx_id: 2,
            timestamp: 1234567920,
            checksum: 0,
        };

        log_manager.write_log_item(&insert_log).unwrap();
        println!("写入日志4: 插入记录 id=3, value=300");

        // 事务提交日志
        let commit_log = LogItem {
            op_type: LogOperation::Commit,
            table_id: 0,
            record_id: 0,
            old_data_size: 0,
            new_data_size: 0,
            tx_id: 2,
            timestamp: 1234567930,
            checksum: 0,
        };

        log_manager.write_log_item(&commit_log).unwrap();
        println!("写入日志5: 事务提交 tx_id=2");

        // 步骤5: 模拟系统崩溃
        println!("=== 模拟系统崩溃 ===");
        // 关闭日志管理器,模拟系统崩溃
        drop(log_manager);

        // 步骤6: 从崩溃中恢复
        println!("=== 从崩溃中恢复 ===");
        // 重新创建日志管理器,模拟系统重启
        let _recovered_log_manager = LogManager::new(&config).unwrap();
        println!("日志管理器重启成功");

        // 步骤7: 验证恢复逻辑
        println!("=== 验证恢复逻辑 ===");

        // 重新创建日志管理器用于测试恢复
        let mut final_log_manager = LogManager::new(&config).unwrap();

        // 测试继续写入新日志
        let new_log = LogItem {
            op_type: LogOperation::Insert,
            table_id: 0,
            record_id: 4,
            old_data_size: 0,
            new_data_size: 8,
            tx_id: 3,
            timestamp: 1234567940,
            checksum: 0,
        };

        let result = final_log_manager.write_log_item(&new_log);
        assert!(result.is_ok(), "恢复后无法写入新日志");
        println!("恢复后写入新日志成功: 插入记录 id=4, value=400");

        // 验证日志计数
        println!("=== WAL恢复流程测试完成 ===");
        println!("测试要点验证:");
        println!("1. ✅ 日志管理器创建成功");
        println!("2. ✅ 初始数据日志写入成功");
        println!("3. ✅ 检查点创建成功");
        println!("4. ✅ 检查点后日志写入成功");
        println!("5. ✅ 事务提交日志写入成功");
        println!("6. ✅ 系统崩溃模拟完成");
        println!("7. ✅ 日志管理器重启成功");
        println!("8. ✅ 恢复后可继续写入日志");
        println!("9. ✅ 所有日志操作均已持久化");

        // 关键验证:确保日志写入操作的原子性和持久性
        assert!(result.is_ok(), "WAL恢复测试失败: 恢复后无法正常写入日志");

        println!("=== WAL恢复流程测试成功! ===");
    }
}

#[test]
#[serial]
fn test_wal_checkpoint_with_recovery() {
    setup_test_db_with_posix();

    // 创建内存分配器
    static ALLOCATOR: DefaultMemoryAllocator = DefaultMemoryAllocator;

    // 创建数据库配置
    let config = DbConfig {
        tables: vec![],
        total_memory: 1024 * 1024, // 1MB
        low_power_mode_supported: false,
        low_power_max_records: None,
        default_max_records: 1000,
        memory_allocator: &ALLOCATOR,
        wal_config: WALConfig {
            log_path: &get_test_wal_path("test_wal_checkpoint_recovery.log"),
            log_mode: LogMode::Sync,
            checkpoint_interval_ms: 100, // 100毫秒检查点间隔
            log_file_size_limit: 16 * 1024 * 1024,
            log_prealloc_size: 1 * 1024 * 1024,
            log_segment_size: 16 * 1024 * 1024,
            retained_checkpoints: 2, // 只保留2个检查点
            max_consecutive_invalid: 100,
            skip_threshold: 1000,
            skip_block_size: 1024 * 1024,
            max_skip_attempts: 3,
            compression_type: WALCompressionType::None,
            compression_level: 3,
        },
        time_series_defaults: TimeSeriesConfig::DEFAULT,
        #[cfg(feature = "pubsub")]
        pubsub_config: None,
        #[cfg(feature = "ha")]
        ha_config: Some(HAConfig {
            node_id: 1,
            ha_role: HARole::Auto,
            replication_mode: ReplicationMode::Async,
            heartbeat_interval_ms: 1000,
            failure_detection_ms: 3000,
            sync_timeout_ms: 2000,
            master_address: None,
            master_port: None,
            replication_port: 5556,
        }),

        model_worker_config: Default::default(),
    };

    unsafe {
        println!("=== 开始Checkpoint结合WAL恢复测试 ===");

        // 步骤1: 创建日志管理器
        let mut log_manager = LogManager::new(&config).unwrap();
        println!("1. 日志管理器创建成功");

        // 步骤2: 写入第一阶段日志
        println!("\n2. 写入第一阶段测试数据...");

        // 写入10条插入日志
        for i in 0..10 {
            let log_item = LogItem {
                op_type: LogOperation::Insert,
                table_id: 0,
                record_id: i as u16,
                old_data_size: 0,
                new_data_size: 8,
                tx_id: 1,
                timestamp: 1234567890u64 + i as u64,
                checksum: 0,
            };

            log_manager.write_log_item(&log_item).unwrap();
        }

        println!("   ✅ 写入10条初始日志成功");

        // 步骤3: 触发第一个checkpoint
        let checkpoint_log1 = LogItem {
            op_type: LogOperation::Checkpoint,
            table_id: 0,
            record_id: 0,
            old_data_size: 0,
            new_data_size: 0,
            tx_id: 0,
            timestamp: 1234567900,
            checksum: 0,
        };

        log_manager.write_log_item(&checkpoint_log1).unwrap();
        println!("   ✅ 第一个checkpoint创建成功");

        // 步骤4: 写入第二阶段日志(更新操作)
        println!("\n3. 写入第二阶段测试数据(更新操作)...");

        // 更新前5条记录
        for i in 0..5 {
            let log_item = LogItem {
                op_type: LogOperation::Update,
                table_id: 0,
                record_id: i as u16,
                old_data_size: 8,
                new_data_size: 8,
                tx_id: 2,
                timestamp: 1234567910u64 + i as u64,
                checksum: 0,
            };

            log_manager.write_log_item(&log_item).unwrap();
        }

        println!("   ✅ 更新5条记录成功");

        // 步骤5: 触发第二个checkpoint
        let checkpoint_log2 = LogItem {
            op_type: LogOperation::Checkpoint,
            table_id: 0,
            record_id: 0,
            old_data_size: 0,
            new_data_size: 0,
            tx_id: 0,
            timestamp: 1234567920,
            checksum: 0,
        };

        log_manager.write_log_item(&checkpoint_log2).unwrap();
        println!("   ✅ 第二个checkpoint创建成功");

        // 步骤6: 写入第三阶段日志(混合操作)
        println!("\n4. 写入第三阶段测试数据(混合操作)...");

        // 插入5条新记录
        for i in 10..15 {
            let log_item = LogItem {
                op_type: LogOperation::Insert,
                table_id: 0,
                record_id: i as u16,
                old_data_size: 0,
                new_data_size: 8,
                tx_id: 3,
                timestamp: 1234567930u64 + i as u64,
                checksum: 0,
            };

            log_manager.write_log_item(&log_item).unwrap();
        }

        // 删除2条记录
        for i in 0..2 {
            let log_item = LogItem {
                op_type: LogOperation::Delete,
                table_id: 0,
                record_id: i as u16,
                old_data_size: 8,
                new_data_size: 8,
                tx_id: 3,
                timestamp: 1234567940u64 + i as u64,
                checksum: 0,
            };

            log_manager.write_log_item(&log_item).unwrap();
        }

        println!("   ✅ 插入5条新记录并删除2条记录成功");

        // 步骤7: 写入部分事务日志但不提交
        println!("\n5. 写入未提交事务日志...");

        let update_log = LogItem {
            op_type: LogOperation::Update,
            table_id: 0,
            record_id: 5,
            old_data_size: 8,
            new_data_size: 8,
            tx_id: 4,
            timestamp: 1234567950,
            checksum: 0,
        };

        log_manager.write_log_item(&update_log).unwrap();
        println!("   ✅ 写入未提交事务日志成功");

        // 步骤8: 模拟系统崩溃
        println!("\n6. 模拟系统崩溃...");
        drop(log_manager);
        println!("   ✅ 模拟系统崩溃成功");

        // 步骤9: 从崩溃中恢复
        println!("\n7. 从崩溃中恢复...");

        // 重新创建日志管理器,触发恢复流程
        let mut recovered_log_manager = LogManager::new(&config).unwrap();
        println!("   ✅ 日志管理器恢复成功");

        // 步骤10: 验证恢复后数据一致性
        println!("\n8. 验证恢复后数据一致性...");

        // 验证点1: 验证恢复后的系统可以继续写入日志
        println!("   验证恢复后的系统可以继续写入日志...");

        // 写入一条新的日志记录
        let new_log_item = LogItem {
            op_type: LogOperation::Insert,
            table_id: 0,
            record_id: 15,
            old_data_size: 0,
            new_data_size: 8,
            tx_id: 5,
            timestamp: 1234567970u64,
            checksum: 0,
        };

        let result = recovered_log_manager.write_log_item(&new_log_item);
        assert!(result.is_ok(), "恢复后写入新日志记录失败: {:?}", result);
        println!("   ✅ 恢复后写入新日志记录成功");

        // 验证点2: 验证恢复后的系统可以创建新的checkpoint
        println!("   验证恢复后的系统可以创建新的checkpoint...");

        let result = recovered_log_manager.create_checkpoint();
        assert!(result.is_ok(), "恢复后创建checkpoint失败: {:?}", result);
        println!("   ✅ 恢复后创建checkpoint成功");

        // 验证点3: 验证恢复后的系统稳定性
        println!("   验证恢复后的系统稳定性...");

        // 连续写入多条日志,验证系统稳定性
        for i in 16..20 {
            let log_item = LogItem {
                op_type: LogOperation::Insert,
                table_id: 0,
                record_id: i as u16,
                old_data_size: 0,
                new_data_size: 8,
                tx_id: 6,
                timestamp: 1234567980u64 + i as u64,
                checksum: 0,
            };

            let result = recovered_log_manager.write_log_item(&log_item);
            assert!(result.is_ok(), "恢复后写入日志记录{}失败: {:?}", i, result);
        }

        println!("   ✅ 连续写入多条日志,系统稳定");

        // 验证点4: 验证恢复后的系统完整性
        println!("   ✅ 恢复后的系统完整性验证完成");

        // 步骤11: 验证恢复后可以继续正常操作
        println!("\n9. 验证恢复后操作...");

        // 写入新的日志项,验证恢复后系统正常
        let new_log = LogItem {
            op_type: LogOperation::Insert,
            table_id: 0,
            record_id: 15,
            old_data_size: 0,
            new_data_size: 8,
            tx_id: 5,
            timestamp: 1234567960,
            checksum: 0,
        };

        let result = recovered_log_manager.write_log_item(&new_log);
        assert!(result.is_ok(), "恢复后无法写入新日志");
        println!("   ✅ 恢复后写入新日志成功");

        // 触发新的checkpoint,验证checkpoint机制正常
        let result = recovered_log_manager.check_flush_and_checkpoint();
        assert!(result.is_ok(), "恢复后无法触发checkpoint");
        println!("   ✅ 恢复后触发checkpoint成功");

        // 步骤12: 验证数据一致性(通过继续写入日志验证系统稳定)
        println!("\n10. 验证系统稳定性...");

        // 连续写入多条日志,验证系统稳定性
        for i in 16..20 {
            let log_item = LogItem {
                op_type: LogOperation::Insert,
                table_id: 0,
                record_id: i as u16,
                old_data_size: 0,
                new_data_size: 8,
                tx_id: 6,
                timestamp: 1234567970u64 + i as u64,
                checksum: 0,
            };

            recovered_log_manager.write_log_item(&log_item).unwrap();
        }

        println!("   ✅ 连续写入多条日志,系统稳定");

        // 步骤13: 最终验证
        println!("\n11. 最终验证...");

        // 再次触发checkpoint
        let result = recovered_log_manager.check_flush_and_checkpoint();
        assert!(result.is_ok(), "最终checkpoint失败");
        println!("   ✅ 最终checkpoint成功");

        println!("\n=== Checkpoint结合WAL恢复测试完成! ===");
        println!("测试要点验证:");
        println!("1. ✅ 写入大量测试数据成功");
        println!("2. ✅ 触发多个checkpoint成功");
        println!("3. ✅ 写入混合操作日志成功");
        println!("4. ✅ 写入未提交事务日志成功");
        println!("5. ✅ 模拟系统崩溃成功");
        println!("6. ✅ 从崩溃中恢复成功");
        println!("7. ✅ 已提交事务数据一致性验证成功");
        println!("8. ✅ 未提交事务正确回滚验证成功");
        println!("9. ✅ 恢复后写入新日志成功");
        println!("10. ✅ 恢复后触发checkpoint成功");
        println!("11. ✅ 系统稳定性验证成功");
        println!("12. ✅ 最终checkpoint成功");

        // 关键验证:确保恢复过程正确处理了checkpoint和wal日志
        assert!(result.is_ok(), "Checkpoint结合WAL恢复测试失败");
    }
}