pi_db 0.19.13

Full cache based database,support transaction
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
//! `KVDBManagerBuilder` äøŽ `KVDBManager` ēš„ēœŸå®žå½“å‰å®žēŽ°å„‘ēŗ¦ēŸ©é˜µć€‚
//!
//! 本 target äøå¼•ē”Øęˆ–čæč”Œę—§ęµ‹čÆ•ć€‚å®ƒä½æē”ØēœŸå®ž 4-worker runtime态
//! `Transaction2PcManager`态`CommitLogger`态Meta/Memory/LogOrdered/LogWrite/Btree å’ŒēœŸå®žäø“ę—¶
//! ę–‡ä»¶ē³»ē»Ÿļ¼ŒéŖŒčÆļ¼š
//!
//! - åÆåŠØč·Æå¾„ć€å†…éƒØ Meta ę³Øå†Œå’Œäŗ”ē±»ē”Øęˆ·č”Øēš„ registry/路径/å±žę€§/ē©ŗč”Øē»Ÿč®”ļ¼›
//! - Memory `persistence=false/true` éƒ½ę— ę•°ę®ē›®å½•ļ¼ŒåŽč€…ä»…č”Øē¤ŗåŠØä½œåÆä»„čæ›å…„ę ¹ WALļ¼›
//! - ē¼ŗč”Øć€éžę³•é•æåŗ¦åē§°ć€å·²åˆ č”Øä»„åŠ Closing/Closed ēŠ¶ę€äø‹ēš„ē®”ē†ęŸ„čÆ¢č¾¹ē•Œļ¼›
//! - åˆ č”ØåŠØä½œē«‹å³ē§»é™¤ registryļ¼Œä½†äøåˆ é™¤åŽŸē‰©ē†ē›®å½•ļ¼Œęäŗ¤ä»čæ›å…„ę ¹ WAL å’Œē”®č®¤é—­ēŽÆļ¼›
//! - 缺蔨 maintenance å½“å‰ēš„ `Ok(())` č¾¹ē•Œļ¼›
//! - `append_new_commit_log` ēœŸå®žč½®ę¢ checkpointļ¼Œä½†äøå¢žåŠ äøšåŠ” WAL 讔数;
//! - listener é€šé“å®žé™…ę‰§č”ŒåŒę­„ę‰¹é‡å›žč°ƒļ¼Œå›žč°ƒęø…ē©ŗäŗ‹ä»¶åŽäøä¼šäæē•™ę—§ę‰¹ę¬”ļ¼›
//! - ꗠ listener ę—¶ęŠ„å‘ŠčÆ·ę±‚čæ”å›ž `ConnectionAborted`ļ¼›
//! - clone å…±äŗ«č½Æå…³é—­ēŠ¶ę€ļ¼Œę–°äŗ‹åŠ”ē«‹å³č¢«ę‹’ē»ļ¼Œä½† close å‰å·²åˆ›å»ŗęˆ–å·²ę³Øå†Œēš„ę™®é€šęäŗ¤ć€åÆę¢å¤
//!   冲突 rollback å’Œē‰ˆęœ¬ęäŗ¤å½“å‰ä»åÆå®Œęˆļ¼Œäø”ęŒä¹…åŒ– Memory ēš„ę ¹ WAL ē»§ē»­čæ›å…„ē”®č®¤é—­ēŽÆć€‚
//!
//! ęœ€åŽäø€é”¹åŖęčæ° `Q-CLOSE-001` / `FIND-CLOSE-001` ēš„å½“å‰å®žēŽ°ļ¼Œäøę˜Æęœ€ē»ˆęˆ–ęœ€ä½³ shutdown
//! 儑约。Btree éžē©ŗ overlay ēš„é•æåŗ¦é£Žé™©ē”± `FIND-TABLE-002` å’ŒåŽē»­č”Øäø“é”¹č“Ÿč“£ļ¼Œęœ¬ target åŖåÆ¹
//! 空 Btree 断言 `0`ļ¼ŒäøęŠŠé”™čÆÆęŠ˜å äøŗ `0` č®¤åÆäøŗę­£ē”®č®¾č®”ć€‚
//!
//! č¢«ęµ‹å…„å£ļ¼š`pi_db::db::{KVDBManagerBuilder, KVDBManager}`怂
//! ę–‡ę”£å…„å£ļ¼š`docs/TEST_AND_BENCHMARK_STRATEGY.md#test-integration`怂

use std::{
    collections::BTreeSet,
    fmt::Debug,
    fs,
    future::Future,
    io::ErrorKind,
    path::{Path, PathBuf},
    time::{Duration, Instant, SystemTime, UNIX_EPOCH},
};

use crossbeam_channel::{bounded, unbounded, Receiver, Sender};
use pi_async_rt::rt::{
    multi_thread::{MultiTaskRuntime, MultiTaskRuntimeBuilder},
    startup_global_time_loop, AsyncRuntime,
};
use pi_async_transaction::{
    manager_2pc::Transaction2PcManager, AsyncCommitLog, ErrorLevel, Transaction2Pc,
};
use pi_atom::Atom;
use pi_bon::{Encode, WriteBuffer};
use pi_db::{
    db::{KVDBManager, KVDBManagerBuilder, KVDBTransaction},
    tables::TableKV,
    utils::{CreateTableOptions, KVDBEvent},
    Binary, KVDBTableType, KVTableMeta, TableKeyVersion, Version, MAX_TABLE_NAME_BYTES,
};
use pi_guid::{Guid, GuidGen};
use pi_sinfo::EnumType;
use pi_store::commit_logger::{CommitLogger, CommitLoggerBuilder};

type TestResult<T = ()> = Result<T, String>;
type RealDb = KVDBManager<usize, CommitLogger>;
type RealTransaction = KVDBTransaction<usize, CommitLogger>;
type RealTrManager = Transaction2PcManager<usize, CommitLogger>;

const META_TABLE: &str = ".tables_meta";
const MEMORY_VOLATILE: &str = "manager_memory_volatile";
const MEMORY_WAL: &str = "manager_memory_wal";
const LOG_ORDERED: &str = "manager_log_ordered";
const LOG_WRITE: &str = "manager_log_write";
const BTREE: &str = "manager_btree";
const MISSING: &str = "manager_missing";
const TEST_TIMEOUT: Duration = Duration::from_secs(60);
const OBSERVATION_TIMEOUT: Duration = Duration::from_secs(10);

/// åœØēœŸå®žē”Ÿäŗ§č£…é…äøŠéŖŒčÆē®”ē†å™Øå½“å‰å„‘ēŗ¦ļ¼Œå¤–å±‚åŒę­„ēœ‹é—Øē‹—é˜²ę­¢ runtime/é”å¼‚åøøę°øä¹…ęŒ‚čµ·ć€‚
#[test]
fn test_manager_current_contract_matrix() {
    let root = TempRoot::new("matrix").expect("creating manager test root must succeed");
    let root_path = root.path().to_path_buf();
    let (event_tx, event_rx) = unbounded();

    run_on_runtime(TEST_TIMEOUT, move |rt| async move {
        let fixture = build_database_with_listener(&rt, &root_path, event_tx).await?;
        verify_startup_and_initial_registry(&fixture, &root_path).await?;
        verify_listener_delivery(&rt, &fixture, &event_rx).await?;
        create_user_tables(&fixture).await?;
        verify_user_table_registry(&fixture).await?;
        verify_missing_and_maintenance_contract(&fixture).await?;
        verify_removed_table_query_contract(&fixture).await?;
        verify_checkpoint_rotation(&fixture).await?;
        verify_no_listener_error(&rt, &root_path).await?;
        verify_soft_close_contract(&fixture).await?;
        Ok(())
    })
    .unwrap_or_else(|error| panic!("manager current contract matrix failed: {error}"));
}

/// éŖŒčÆåÆåŠØåˆ›å»ŗēš„äø‰äøŖč·Æå¾„å’ŒåŖå«å†…éƒØ Meta ēš„åˆå§‹ registry怂
async fn verify_startup_and_initial_registry(fixture: &Fixture, root: &Path) -> TestResult<()> {
    let db_path = root.join("database");
    expect_eq("db_path", &fixture.db.db_path(), &&*db_path)?;
    expect_eq(
        "tables_meta_path",
        &fixture.db.tables_meta_path(),
        &&*db_path.join(META_TABLE),
    )?;
    expect_eq(
        "tables_path",
        &fixture.db.tables_path(),
        &&*db_path.join(".tables"),
    )?;

    require(
        fixture.db.tables_meta_path().is_dir(),
        "startup did not create the Meta directory",
    )?;
    require(
        fixture.db.tables_path().is_dir(),
        "startup did not create the user-table directory",
    )?;
    expect_eq("initial table_size", &fixture.db.table_size().await, &1)?;
    expect_table_names(&fixture.db, &[META_TABLE]).await?;

    let meta = Atom::from(META_TABLE);
    expect_eq("Meta existence", &fixture.db.is_exist(&meta).await, &true)?;
    expect_eq(
        "Meta path",
        &fixture.db.table_path(&meta).await,
        &Some(fixture.db.tables_meta_path().to_path_buf()),
    )?;
    expect_eq(
        "Meta persistence",
        &fixture.db.is_persistent_table(&meta).await,
        &Some(true),
    )?;
    expect_eq(
        "Meta ordering",
        &fixture.db.is_ordered_table(&meta).await,
        &Some(true),
    )?;
    expect_eq(
        "initial Meta record count",
        &fixture.db.table_record_size(&meta).await,
        &Some(0),
    )?;
    expect_eq(
        "initial Meta cache bytes",
        &fixture.db.table_cache_size(&meta).await,
        &Some(0),
    )?;
    expect_eq(
        "initial transaction registry",
        &fixture.tr_manager.transaction_len(),
        &0,
    )?;
    Ok(())
}

/// å‘é€äø¤äøŖęœ‰ę˜Žē”®ē”®č®¤ē‚¹ēš„ęŠ„å‘ŠčÆ·ę±‚ļ¼ŒéŖŒčÆäŗ‹ä»¶å®žé™…åˆ°č¾¾äø”ęÆę‰¹ē”±å›žč°ƒ drain怂
async fn verify_listener_delivery(
    rt: &MultiTaskRuntime<()>,
    fixture: &Fixture,
    event_rx: &Receiver<EventObservation>,
) -> TestResult<()> {
    for sequence in 1..=2 {
        fixture
            .db
            .report_transaction_info()
            .await
            .map_err(|error| format!("report request {sequence} was rejected: {error}"))?;
        let observed = wait_for_report(rt, event_rx, OBSERVATION_TIMEOUT).await?;
        expect_eq(
            &format!("report batch {sequence} total event count"),
            &observed.total,
            &1,
        )?;
        expect_eq(
            &format!("report batch {sequence} report count"),
            &observed.reports,
            &1,
        )?;
        expect_eq(
            &format!("report batch {sequence} commit-failed count"),
            &observed.commit_failed,
            &0,
        )?;
        expect_eq(
            &format!("report batch {sequence} confirmed count"),
            &observed.confirmed,
            &0,
        )?;
        expect_eq(
            &format!("report batch {sequence} transaction count"),
            &observed.transaction_len,
            &0,
        )?;
        expect_eq(
            &format!("report batch {sequence} manager path"),
            &observed.db_path,
            &fixture.db.db_path().to_path_buf(),
        )?;
    }
    Ok(())
}

/// åœØäø€äøŖēœŸå®ž DDL ę ¹äŗ‹åŠ”äø­åˆ›å»ŗäø¤ē§ Memory é…ē½®å’Œäø‰ē§ęŒä¹…åŒ–č”Øć€‚
async fn create_user_tables(fixture: &Fixture) -> TestResult<()> {
    let transaction = transaction(&fixture.db, "manager DDL", true, 10_000, 10_000)?;
    let tables = [
        (
            MEMORY_VOLATILE,
            table_meta(KVDBTableType::MemOrdTab, false),
            CreateTableOptions::Empty,
        ),
        (
            MEMORY_WAL,
            table_meta(KVDBTableType::MemOrdTab, true),
            CreateTableOptions::Empty,
        ),
        (
            LOG_ORDERED,
            table_meta(KVDBTableType::LogOrdTab, true),
            CreateTableOptions::LogOrdTab(64 * 1024 * 1024, 1024 * 1024, 1024 * 1024),
        ),
        (
            LOG_WRITE,
            table_meta(KVDBTableType::LogWTab, true),
            CreateTableOptions::Empty,
        ),
        (
            BTREE,
            table_meta(KVDBTableType::BtreeOrdTab, true),
            CreateTableOptions::BtreeOrdTab(4 * 1024 * 1024, false),
        ),
    ];

    for (name, meta, options) in tables {
        transaction
            .create_table_with_options(Atom::from(name), meta, options, false)
            .await
            .map_err(|error| format!("creating {name} failed: {error}"))?;
    }

    let append_before = fixture.logger.append_total_count();
    let confirmation_before = confirmation_accounting_snapshot(&fixture.logger).await?;
    commit_transaction(&transaction, "manager DDL").await?;
    expect_eq(
        "DDL root WAL append count",
        &fixture.logger.append_total_count(),
        &(append_before + 1),
    )?;
    expect_eq(
        "DDL confirmation accounting",
        &confirmation_accounting_snapshot(&fixture.logger).await?,
        &(confirmation_before + 1),
    )
}

/// 验证 hash registryć€é€č”Øå±žę€§ć€ē›®å½•å’Œē©ŗč”Øē»Ÿč®”ēš„ē²¾ē”®ēŸ©é˜µć€‚
async fn verify_user_table_registry(fixture: &Fixture) -> TestResult<()> {
    let expected = [
        META_TABLE,
        MEMORY_VOLATILE,
        MEMORY_WAL,
        LOG_ORDERED,
        LOG_WRITE,
        BTREE,
    ];
    expect_eq("table_size after DDL", &fixture.db.table_size().await, &6)?;
    expect_table_names(&fixture.db, &expected).await?;

    let expected_properties = [
        (
            META_TABLE,
            true,
            true,
            Some(fixture.db.tables_meta_path().to_path_buf()),
        ),
        (MEMORY_VOLATILE, false, true, None),
        (MEMORY_WAL, true, true, None),
        (
            LOG_ORDERED,
            true,
            true,
            Some(fixture.db.tables_path().join(LOG_ORDERED)),
        ),
        (
            LOG_WRITE,
            true,
            true,
            Some(fixture.db.tables_path().join(LOG_WRITE)),
        ),
        (
            BTREE,
            true,
            true,
            Some(fixture.db.tables_path().join(BTREE).join("table.dat")),
        ),
    ];

    for (name, persistent, ordered, path) in expected_properties {
        let atom = Atom::from(name);
        expect_eq(
            &format!("{name} existence"),
            &fixture.db.is_exist(&atom).await,
            &true,
        )?;
        expect_eq(
            &format!("{name} persistence"),
            &fixture.db.is_persistent_table(&atom).await,
            &Some(persistent),
        )?;
        expect_eq(
            &format!("{name} ordering"),
            &fixture.db.is_ordered_table(&atom).await,
            &Some(ordered),
        )?;
        expect_eq(
            &format!("{name} path"),
            &fixture.db.table_path(&atom).await,
            &path,
        )?;
    }

    require(
        !fixture.db.tables_path().join(MEMORY_VOLATILE).exists(),
        "volatile Memory unexpectedly created a data directory",
    )?;
    require(
        !fixture.db.tables_path().join(MEMORY_WAL).exists(),
        "persistence=true Memory unexpectedly created a data directory",
    )?;
    for name in [LOG_ORDERED, LOG_WRITE, BTREE] {
        require(
            fixture.db.tables_path().join(name).is_dir(),
            &format!("persistent table directory for {name} is missing"),
        )?;
    }

    expect_eq(
        "Meta record count after five creates",
        &fixture.db.table_record_size(&Atom::from(META_TABLE)).await,
        &Some(5),
    )?;
    let meta_cache = fixture
        .db
        .table_cache_size(&Atom::from(META_TABLE))
        .await
        .ok_or_else(|| "Meta cache size unexpectedly missing".to_owned())?;
    require(meta_cache > 0, "Meta cache stayed empty after five creates")?;

    for name in [MEMORY_VOLATILE, MEMORY_WAL, LOG_ORDERED, LOG_WRITE, BTREE] {
        let atom = Atom::from(name);
        expect_eq(
            &format!("empty {name} record count"),
            &fixture.db.table_record_size(&atom).await,
            &Some(0),
        )?;
        expect_eq(
            &format!("empty {name} cache bytes"),
            &fixture.db.table_cache_size(&atom).await,
            &Some(0),
        )?;
    }
    Ok(())
}

/// éŖŒčÆē¼ŗč”Øēš„ę‰€ęœ‰ęŸ„čÆ¢ē»“ęžœļ¼Œä»„åŠē¼ŗč”Ø/Memory maintenance ēš„å½“å‰ę— ę“ä½œčÆ­ä¹‰ć€‚
async fn verify_missing_and_maintenance_contract(fixture: &Fixture) -> TestResult<()> {
    let missing = Atom::from(MISSING);
    expect_eq(
        "missing existence",
        &fixture.db.is_exist(&missing).await,
        &false,
    )?;
    expect_eq(
        "missing path",
        &fixture.db.table_path(&missing).await,
        &None,
    )?;
    expect_eq(
        "missing persistence",
        &fixture.db.is_persistent_table(&missing).await,
        &None,
    )?;
    expect_eq(
        "missing ordering",
        &fixture.db.is_ordered_table(&missing).await,
        &None,
    )?;
    expect_eq(
        "missing record count",
        &fixture.db.table_record_size(&missing).await,
        &None,
    )?;
    expect_eq(
        "missing cache bytes",
        &fixture.db.table_cache_size(&missing).await,
        &None,
    )?;
    assert_absent_table_queries(fixture, &Atom::from(""), "empty table name", 6).await?;
    assert_absent_table_queries(
        fixture,
        &Atom::from("x".repeat(MAX_TABLE_NAME_BYTES + 1)),
        "over-limit table name",
        6,
    )
    .await?;
    fixture
        .db
        .ready_collect_table(&missing)
        .await
        .map_err(|error| format!("missing ready_collect was not a no-op: {error}"))?;
    fixture
        .db
        .collect_table(&missing)
        .await
        .map_err(|error| format!("missing collect was not a no-op: {error}"))?;

    let memory = Atom::from(MEMORY_VOLATILE);
    fixture
        .db
        .ready_collect_table(&memory)
        .await
        .map_err(|error| format!("Memory ready_collect no-op failed: {error}"))?;
    fixture
        .db
        .collect_table(&memory)
        .await
        .map_err(|error| format!("Memory collect no-op failed: {error}"))?;
    expect_eq(
        "Memory record count after maintenance",
        &fixture.db.table_record_size(&memory).await,
        &Some(0),
    )
}

/// éŖŒčÆåˆ č”Øēš„ registry åÆč§ę€§ć€ęŸ„čÆ¢čæ”å›žć€ē‰©ē†ē›®å½•éžē›®ę ‡åŠę ¹ WAL ē”®č®¤é—­ēŽÆć€‚
async fn verify_removed_table_query_contract(fixture: &Fixture) -> TestResult<()> {
    let table = Atom::from(LOG_ORDERED);
    let physical_path = fixture.db.tables_path().join(LOG_ORDERED);
    require(
        physical_path.is_dir(),
        "LogOrdered physical directory was missing before removal",
    )?;

    let transaction = transaction(&fixture.db, "manager remove table", true, 10_000, 10_000)?;
    let append_before = fixture.logger.append_total_count();
    let confirmation_before = confirmation_accounting_snapshot(&fixture.logger).await?;
    transaction
        .remove_table(table.clone())
        .await
        .map_err(|error| format!("staging manager table removal failed: {error}"))?;

    assert_absent_table_queries(fixture, &table, "staged removed table", 5).await?;
    expect_eq(
        "remove action WAL append count",
        &fixture.logger.append_total_count(),
        &append_before,
    )?;
    require(
        physical_path.is_dir(),
        "remove action unexpectedly deleted the LogOrdered physical directory",
    )?;

    commit_transaction(&transaction, "manager remove table").await?;
    assert_absent_table_queries(fixture, &table, "committed removed table", 5).await?;
    expect_eq(
        "remove commit WAL append count",
        &fixture.logger.append_total_count(),
        &(append_before + 1),
    )?;
    expect_eq(
        "remove commit confirmation accounting",
        &confirmation_accounting_snapshot(&fixture.logger).await?,
        &(confirmation_before + 1),
    )?;
    require(
        physical_path.is_dir(),
        "committed removal unexpectedly deleted the LogOrdered physical directory",
    )
}

/// åÆ¹ä»»ę„ęœŖę³Øå†Œåē§°éŖŒčÆę‰€ęœ‰é€č”Øē®”ē†ęŸ„čÆ¢éƒ½ä½æē”ØåŒäø€ā€œē¼ŗč”Øā€ē»“ęžœć€‚
async fn assert_absent_table_queries(
    fixture: &Fixture,
    table: &Atom,
    label: &str,
    expected_table_size: usize,
) -> TestResult<()> {
    expect_eq(
        &format!("{label} existence"),
        &fixture.db.is_exist(table).await,
        &false,
    )?;
    expect_eq(
        &format!("{label} path"),
        &fixture.db.table_path(table).await,
        &None,
    )?;
    expect_eq(
        &format!("{label} persistence"),
        &fixture.db.is_persistent_table(table).await,
        &None,
    )?;
    expect_eq(
        &format!("{label} ordering"),
        &fixture.db.is_ordered_table(table).await,
        &None,
    )?;
    expect_eq(
        &format!("{label} record count"),
        &fixture.db.table_record_size(table).await,
        &None,
    )?;
    expect_eq(
        &format!("{label} cache bytes"),
        &fixture.db.table_cache_size(table).await,
        &None,
    )?;
    expect_eq(
        &format!("{label} table count"),
        &fixture.db.table_size().await,
        &expected_table_size,
    )?;
    require(
        !fixture.db.tables().await.iter().any(|name| name == table),
        &format!("{label} unexpectedly appeared in tables()"),
    )
}

/// 验证 manager checkpoint API äøŽ logger åÆč§‚ęµ‹é‡äø„ę ¼äø€č‡“ć€‚
async fn verify_checkpoint_rotation(fixture: &Fixture) -> TestResult<()> {
    let before_index = fixture.logger.current_check_point().await;
    let append_count = fixture.logger.append_total_count();
    let confirm_count = fixture.logger.confirm_total_count();
    let waiting_count = fixture.logger.waiting_confirm_count().await;

    let first = fixture
        .db
        .append_new_commit_log()
        .await
        .map_err(|error| format!("first checkpoint rotation failed: {error}"))?;
    expect_eq(
        "first current checkpoint",
        &fixture.logger.current_check_point().await,
        &(first + 1),
    )?;
    expect_eq("first checkpoint allocation", &first, &before_index)?;

    let second = fixture
        .db
        .append_new_commit_log()
        .await
        .map_err(|error| format!("second checkpoint rotation failed: {error}"))?;
    expect_eq(
        "second current checkpoint",
        &fixture.logger.current_check_point().await,
        &(second + 1),
    )?;
    expect_eq("second checkpoint increment", &second, &(first + 1))?;
    expect_eq(
        "checkpoint rotation business append count",
        &fixture.logger.append_total_count(),
        &append_count,
    )?;
    expect_eq(
        "checkpoint rotation confirm count",
        &fixture.logger.confirm_total_count(),
        &confirm_count,
    )?;
    expect_eq(
        "checkpoint rotation waiting count",
        &fixture.logger.waiting_confirm_count().await,
        &waiting_count,
    )
}

/// ä½æē”Øē¬¬äŗŒäøŖēœŸå®žę•°ę®åŗ“éŖŒčÆęœŖé…ē½® listener ēš„é”™čÆÆåˆ†ē±»ć€‚
async fn verify_no_listener_error(rt: &MultiTaskRuntime<()>, root: &Path) -> TestResult<()> {
    let no_listener_root = root.join("no-listener");
    let fixture = build_database(rt, &no_listener_root).await?;
    let error = fixture
        .db
        .report_transaction_info()
        .await
        .expect_err("reporting without a listener must fail");
    expect_eq(
        "no-listener report error kind",
        &error.kind(),
        &ErrorKind::ConnectionAborted,
    )?;
    fixture.db.close();
    Ok(())
}

/// 验证 close ēš„åÆč§‚åÆŸč½Æå…³é—­č”Œäøŗļ¼ŒäøęŠŠå®ƒę‰©å¤§ęˆå®Œę•“ shutdown äæčÆć€‚
async fn verify_soft_close_contract(fixture: &Fixture) -> TestResult<()> {
    let ordinary_key = encode_usize(51_001);
    let ordinary_value = encode_usize(61_001);
    let rejected_value = encode_usize(61_002);
    let version_key = encode_usize(51_002);
    let version_value = encode_usize(61_003);

    let precreated = transaction(&fixture.db, "created before close", true, 0, 0)?;
    let observer = transaction(&fixture.db, "observer created before close", false, 0, 0)?;
    let active = transaction(&fixture.db, "ordinary registered before close", true, 0, 0)?;
    let rollback = transaction(&fixture.db, "rollback registered before close", true, 0, 0)?;
    let version = transaction(&fixture.db, "version registered before close", true, 0, 0)?;
    let produced_before = fixture.tr_manager.produced_transaction_total();
    let consumed_before = fixture.tr_manager.consumed_transaction_total();
    let append_before = fixture.logger.append_total_count();
    let confirmation_before = confirmation_accounting_snapshot(&fixture.logger).await?;

    active
        .upsert(vec![TableKV::new(
            Atom::from(MEMORY_VOLATILE),
            ordinary_key.clone(),
            Some(ordinary_value.clone()),
        )])
        .await
        .map_err(|error| format!("staging ordinary close write failed: {error:?}"))?;
    let active_prepare = active
        .prepare_modified_conflicts()
        .await
        .map_err(|error| format!("preparing active close transaction failed: {error:?}"))?;

    rollback
        .upsert(vec![TableKV::new(
            Atom::from(MEMORY_VOLATILE),
            ordinary_key.clone(),
            Some(rejected_value),
        )])
        .await
        .map_err(|error| format!("staging rollback close write failed: {error:?}"))?;
    let rollback_error = rollback
        .prepare_modified_conflicts()
        .await
        .expect_err("the competing ordinary transaction must fail before close");
    require(
        rollback_error.is_conflicts()
            && !rollback_error.is_all_conflicts()
            && matches!(rollback_error.level(), ErrorLevel::Normal),
        &format!(
            "competing ordinary transaction returned an invalid error: {rollback_error:?}"
        ),
    )?;
    let rollback_conflict = rollback_error
        .conflicts()
        .ok_or_else(|| "ordinary conflict did not expose its table and key".to_owned())?;
    expect_eq(
        "ordinary close conflict table",
        &rollback_conflict.0.as_str(),
        &MEMORY_VOLATILE,
    )?;
    expect_eq(
        "ordinary close conflict key",
        rollback_conflict.1,
        &ordinary_key,
    )?;

    let (initial_version_value, initial_version) = fixture
        .db
        .query_with_version(Atom::from(MEMORY_WAL), version_key.clone())
        .await
        .map_err(|error| format!("loading close version baseline failed: {error:?}"))?;
    expect_eq(
        "close version baseline value",
        &initial_version_value,
        &None,
    )?;
    require(
        matches!(&initial_version, Version::Delete(_)),
        &format!(
            "absent close version baseline was not Delete: {initial_version:?}"
        ),
    )?;
    let version_prepare = version
        .prepare_with_version(
            vec![TableKeyVersion {
                table: Atom::from(MEMORY_WAL),
                key: version_key.clone(),
                version: initial_version,
            }],
            vec![TableKV::new(
                Atom::from(MEMORY_WAL),
                version_key.clone(),
                Some(version_value.clone()),
            )],
        )
        .await
        .map_err(|error| format!("preparing version close transaction failed: {error:?}"))?;
    let version_uid = version
        .get_transaction_uid()
        .ok_or_else(|| "version close prepare did not allocate a transaction UID".to_owned())?;

    expect_eq(
        "active transaction registry before close",
        &fixture.tr_manager.transaction_len(),
        &3,
    )?;

    fixture.db.clone().close();
    verify_management_queries_after_close(fixture, "Closing").await?;
    require(
        fixture
            .db
            .transaction(Atom::from("created after close"), true, 1, 1)
            .is_none(),
        "close did not reject a new transaction",
    )?;
    fixture.db.close();

    active
        .commit_modified(active_prepare)
        .await
        .map_err(|error| format!("active transaction could not finish after close: {error:?}"))?;
    rollback
        .rollback_modified()
        .await
        .map_err(|error| format!("failed transaction could not rollback after close: {error:?}"))?;
    let receipt = version
        .commit_with_version(version_prepare)
        .await
        .map_err(|error| format!("version transaction could not finish after close: {error:?}"))?;
    expect_eq("close version receipt count", &receipt.len(), &1usize)?;
    expect_eq(
        "close version receipt table",
        &receipt[0].table.as_str(),
        &MEMORY_WAL,
    )?;
    expect_eq(
        "close version receipt key",
        &receipt[0].key,
        &version_key,
    )?;
    expect_eq(
        "close version receipt version",
        &receipt[0].version,
        &Version::Upsert(version_uid),
    )?;
    expect_eq(
        "active transaction registry after close completions",
        &fixture.tr_manager.transaction_len(),
        &0,
    )?;

    let precreated_prepare = precreated.prepare_modified().await.map_err(|error| {
        format!("pre-created transaction could not prepare after close: {error:?}")
    })?;
    precreated
        .commit_modified(precreated_prepare)
        .await
        .map_err(|error| {
            format!("pre-created transaction could not commit after close: {error:?}")
        })?;

    let observed = observer
        .query(vec![
            TableKV::new(
                Atom::from(MEMORY_VOLATILE),
                ordinary_key,
                None,
            ),
            TableKV::new(
                Atom::from(MEMORY_WAL),
                version_key,
                None,
            ),
        ])
        .await;
    expect_eq("close observer result count", &observed.len(), &2usize)?;
    expect_eq(
        "ordinary committed value after close",
        &observed[0],
        &Some(ordinary_value),
    )?;
    expect_eq(
        "version committed value after close",
        &observed[1],
        &Some(version_value),
    )?;

    expect_eq(
        "close lifecycle produced count",
        &fixture.tr_manager.produced_transaction_total(),
        &(produced_before + 4),
    )?;
    expect_eq(
        "close lifecycle consumed count",
        &fixture.tr_manager.consumed_transaction_total(),
        &(consumed_before + 4),
    )?;
    expect_eq(
        "close lifecycle final transaction registry",
        &fixture.tr_manager.transaction_len(),
        &0,
    )?;
    expect_eq(
        "close lifecycle WAL append count",
        &fixture.logger.append_total_count(),
        &(append_before + 1),
    )?;
    expect_eq(
        "close lifecycle confirmation accounting",
        &confirmation_accounting_snapshot(&fixture.logger).await?,
        &(confirmation_before + 1),
    )?;

    fixture.db.close();
    verify_management_queries_after_close(fixture, "Closed").await?;
    require(
        fixture
            .db
            .transaction(Atom::from("created after repeated close"), false, 0, 0)
            .is_none(),
        "repeated close unexpectedly reopened the database",
    )
}

/// ē®”ē†ęŸ„čÆ¢äøčÆ»å–č½Æå…³é—­ēŠ¶ę€ļ¼›Closing 和 Closed éƒ½ē»§ē»­ęš“éœ²åŒäø€ registry å½“å‰å€¼ć€‚
async fn verify_management_queries_after_close(
    fixture: &Fixture,
    phase: &str,
) -> TestResult<()> {
    expect_eq(
        &format!("{phase} Meta path derivation"),
        &fixture.db.tables_meta_path(),
        &&*fixture.db.db_path().join(META_TABLE),
    )?;
    expect_eq(
        &format!("{phase} user-table path derivation"),
        &fixture.db.tables_path(),
        &&*fixture.db.db_path().join(".tables"),
    )?;
    expect_eq(
        &format!("{phase} table count"),
        &fixture.db.table_size().await,
        &5usize,
    )?;
    expect_table_names(
        &fixture.db,
        &[META_TABLE, MEMORY_VOLATILE, MEMORY_WAL, LOG_WRITE, BTREE],
    )
    .await?;

    expect_eq(
        &format!("{phase} existing table"),
        &fixture.db.is_exist(&Atom::from(MEMORY_WAL)).await,
        &true,
    )?;
    expect_eq(
        &format!("{phase} Btree path"),
        &fixture.db.table_path(&Atom::from(BTREE)).await,
        &Some(fixture.db.tables_path().join(BTREE).join("table.dat")),
    )?;
    expect_eq(
        &format!("{phase} volatile Memory persistence"),
        &fixture
            .db
            .is_persistent_table(&Atom::from(MEMORY_VOLATILE))
            .await,
        &Some(false),
    )?;
    expect_eq(
        &format!("{phase} Btree ordering"),
        &fixture.db.is_ordered_table(&Atom::from(BTREE)).await,
        &Some(true),
    )?;
    expect_eq(
        &format!("{phase} Meta record count"),
        &fixture.db.table_record_size(&Atom::from(META_TABLE)).await,
        &Some(4),
    )?;
    require(
        fixture
            .db
            .table_cache_size(&Atom::from(META_TABLE))
            .await
            .is_some_and(|size| size > 0),
        &format!("{phase} Meta cache bytes were absent or zero"),
    )?;
    assert_absent_table_queries(fixture, &Atom::from(LOG_ORDERED), phase, 5).await
}

/// 等待 listener å›žč°ƒå®žé™…äŗ¤ä»˜äø€äøŖå«ęŠ„å‘ŠčÆ·ę±‚ēš„ę‰¹ę¬”ć€‚
async fn wait_for_report(
    rt: &MultiTaskRuntime<()>,
    event_rx: &Receiver<EventObservation>,
    timeout: Duration,
) -> TestResult<EventObservation> {
    let deadline = Instant::now() + timeout;
    loop {
        match event_rx.try_recv() {
            Ok(observation) if observation.reports > 0 => return Ok(observation),
            Ok(observation) => {
                return Err(format!(
                    "listener delivered a batch without the requested report: {observation:?}"
                ));
            }
            Err(crossbeam_channel::TryRecvError::Disconnected) => {
                return Err("listener observation channel disconnected".to_owned());
            }
            Err(crossbeam_channel::TryRecvError::Empty) => {}
        }
        if Instant::now() >= deadline {
            return Err(format!("listener did not run within {timeout:?}"));
        }
        rt.timeout(1).await;
    }
}

/// ęÆ”č¾ƒ registry åē§°é›†åˆļ¼Œę˜Žē”®åæ½ē•„ hash map ēš„äøēØ³å®ščæ­ä»£é”ŗåŗć€‚
async fn expect_table_names(db: &RealDb, expected: &[&str]) -> TestResult<()> {
    let actual = db
        .tables()
        .await
        .into_iter()
        .map(|name| name.as_str().to_owned())
        .collect::<BTreeSet<_>>();
    let expected = expected
        .iter()
        .map(|name| (*name).to_owned())
        .collect::<BTreeSet<_>>();
    expect_eq("table name set", &actual, &expected)
}

fn table_meta(table_type: KVDBTableType, persistence: bool) -> KVTableMeta {
    KVTableMeta::new(table_type, persistence, EnumType::Usize, EnumType::Usize)
}

fn encode_usize(value: usize) -> Binary {
    let mut buffer = WriteBuffer::new();
    value.encode(&mut buffer);
    Binary::new(buffer.bytes)
}

/// `CommitLogger` åœØåŒäø€ę£€ęŸ„ē‚¹é”å†…ęŠŠäø€äøŖäŗ‹åŠ”ä»Ž waiting 转移到 confirmed怂
///
/// ꌇꠇ API åˆ†å¼€ęš“éœ²äø¤äøŖč®”ę•°ļ¼Œē›“ęŽ„å„čÆ»äø€ę¬”åÆčƒ½ę’žäøŠč½¬ē§»äø­é—“ę€ć€‚čæ™é‡Œä»…åœØē”®č®¤ē“Æč®”å€¼å‰åŽ
/// äø€č‡“ę—¶ęŽ„å—å¤¹åœØäø­é—“ēš„ waiting čÆ»ę•°ļ¼Œä»Žč€Œå¾—åˆ°ęŸäø€ēØ³å®šēž¬é—“ēš„å®ˆę’ę€»é‡ļ¼›äøē­‰å¾…é˜Ÿåˆ—ęø…ē©ŗļ¼Œ
/// ä¹ŸäøęŠŠ Manager ēš„č½Æå…³é—­čÆ­ä¹‰ę‰©å¤§ęˆ graceful shutdown怂
async fn confirmation_accounting_snapshot(logger: &CommitLogger) -> TestResult<usize> {
    let deadline = Instant::now() + OBSERVATION_TIMEOUT;
    loop {
        let confirmed_before = logger.confirm_total_count();
        let waiting = logger.waiting_confirm_count().await;
        let confirmed_after = logger.confirm_total_count();
        if confirmed_before == confirmed_after {
            return confirmed_after
                .checked_add(waiting)
                .ok_or_else(|| "CommitLogger confirmation accounting overflowed usize".to_owned());
        }

        if Instant::now() >= deadline {
            return Err(format!(
                "CommitLogger confirmation accounting did not reach a stable observation within {:?}",
                OBSERVATION_TIMEOUT
            ));
        }
    }
}

fn transaction(
    db: &RealDb,
    source: &str,
    writable: bool,
    prepare_timeout: u64,
    commit_timeout: u64,
) -> TestResult<RealTransaction> {
    db.transaction(
        Atom::from(source),
        writable,
        prepare_timeout,
        commit_timeout,
    )
    .ok_or_else(|| format!("database rejected transaction {source}"))
}

async fn commit_transaction(transaction: &RealTransaction, label: &str) -> TestResult<()> {
    let prepare = transaction
        .prepare_modified()
        .await
        .map_err(|error| format!("preparing {label} failed: {error:?}"))?;
    transaction
        .commit_modified(prepare)
        .await
        .map_err(|error| format!("committing {label} failed: {error:?}"))
}

/// ęž„å»ŗåø¦ēœŸå®ž listener ēš„ę•°ę®åŗ“ļ¼Œå¹¶ęŠŠęÆę¬” drain åŽēš„ę‰¹ę¬”ę‘˜č¦å‘é€ē»™ęµ‹čÆ•ēŗæēØ‹ć€‚
async fn build_database_with_listener(
    rt: &MultiTaskRuntime<()>,
    root: &Path,
    event_tx: Sender<EventObservation>,
) -> TestResult<Fixture> {
    let (tr_manager, logger) = build_transaction_manager(rt, root).await?;
    let db_path = root.join("database");
    let db = KVDBManagerBuilder::new(rt.clone(), tr_manager.clone(), &db_path)
        .startup_with_listener(
            false,
            Some(
                move |db: &RealDb, manager: &RealTrManager, events: &mut Vec<KVDBEvent<Guid>>| {
                    let mut observation = EventObservation {
                        total: events.len(),
                        reports: 0,
                        commit_failed: 0,
                        confirmed: 0,
                        transaction_len: manager.transaction_len(),
                        db_path: db.db_path().to_path_buf(),
                    };
                    for event in events.drain(..) {
                        if event.is_report_transaction_info() {
                            observation.reports += 1;
                        } else if event.is_commit_failed() {
                            observation.commit_failed += 1;
                        } else if event.is_confirm_commited() {
                            observation.confirmed += 1;
                        }
                    }
                    let _ = event_tx.send(observation);
                },
            ),
        )
        .await
        .map_err(|error| format!("starting listener database at {db_path:?} failed: {error}"))?;
    Ok(Fixture {
        db,
        tr_manager,
        logger,
    })
}

/// ęž„å»ŗę—  listener ēš„åÆ¹ē…§ę•°ę®åŗ“ć€‚
async fn build_database(rt: &MultiTaskRuntime<()>, root: &Path) -> TestResult<Fixture> {
    let (tr_manager, logger) = build_transaction_manager(rt, root).await?;
    let db_path = root.join("database");
    let db = KVDBManagerBuilder::new(rt.clone(), tr_manager.clone(), &db_path)
        .startup(false)
        .await
        .map_err(|error| format!("starting database at {db_path:?} failed: {error}"))?;
    Ok(Fixture {
        db,
        tr_manager,
        logger,
    })
}

async fn build_transaction_manager(
    rt: &MultiTaskRuntime<()>,
    root: &Path,
) -> TestResult<(RealTrManager, CommitLogger)> {
    fs::create_dir_all(root)
        .map_err(|error| format!("creating manager fixture root {root:?} failed: {error}"))?;
    let wal_path = root.join("root-wal");
    let logger = CommitLoggerBuilder::new(rt.clone(), &wal_path)
        .log_file_limit(64 * 1024 * 1024)
        .collect_interval(5 * 60 * 1000)
        .build()
        .await
        .map_err(|error| format!("building CommitLogger at {wal_path:?} failed: {error}"))?;
    let manager = Transaction2PcManager::new(
        rt.clone(),
        GuidGen::new(0, std::process::id() as u16),
        logger.clone(),
    );
    Ok((manager, logger))
}

fn run_on_runtime<T, F, Fut>(timeout: Duration, build: F) -> TestResult<T>
where
    T: Send + 'static,
    F: FnOnce(MultiTaskRuntime<()>) -> Fut,
    Fut: Future<Output = TestResult<T>> + Send + 'static,
{
    let _time_loop = startup_global_time_loop(10);
    let rt = MultiTaskRuntimeBuilder::default()
        .init_worker_size(4)
        .build();
    let future = build(rt.clone());
    let (result_tx, result_rx) = bounded(1);

    rt.spawn(async move {
        let _ = result_tx.send(future.await);
    })
    .map_err(|error| format!("spawning manager contract future failed: {error:?}"))?;

    result_rx
        .recv_timeout(timeout)
        .map_err(|error| format!("manager contract future exceeded {timeout:?}: {error}"))?
}

fn expect_eq<T: Debug + PartialEq>(label: &str, actual: &T, expected: &T) -> TestResult<()> {
    if actual == expected {
        Ok(())
    } else {
        Err(format!(
            "{label}: expected {expected:?}, observed {actual:?}"
        ))
    }
}

fn require(condition: bool, message: &str) -> TestResult<()> {
    if condition {
        Ok(())
    } else {
        Err(message.to_owned())
    }
}

struct Fixture {
    db: RealDb,
    tr_manager: RealTrManager,
    logger: CommitLogger,
}

#[derive(Debug)]
struct EventObservation {
    total: usize,
    reports: usize,
    commit_failed: usize,
    confirmed: usize,
    transaction_len: usize,
    db_path: PathBuf,
}

struct TempRoot {
    path: PathBuf,
}

impl TempRoot {
    fn new(label: &str) -> TestResult<Self> {
        let nanos = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .map_err(|error| format!("system time is before UNIX_EPOCH: {error}"))?
            .as_nanos();
        let path = std::env::temp_dir().join(format!(
            "pi_db_manager_contract_{label}_{}_{}",
            std::process::id(),
            nanos
        ));
        fs::create_dir_all(&path)
            .map_err(|error| format!("creating temporary root {path:?} failed: {error}"))?;
        Ok(Self { path })
    }

    fn path(&self) -> &Path {
        &self.path
    }
}

impl Drop for TempRoot {
    fn drop(&mut self) {
        let _ = fs::remove_dir_all(&self.path);
    }
}