msime-engine 0.2.0

Input method engine for Chinese and other languages: quanpin, shuangpin, nine-key, wubi, zhuyin, Cantonese, Japanese, Korean and more, ranked over a word lattice with typo correction and learning from what the user picks. The engine of 水杉输入法 (Metasequoia IME).
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
//! Typo learning and autocorrect suppression (user-dictionary.md §10.3, quanpin.md §7.8). The profile is a per-journal snapshot shared by the process and reloaded when the journal or its `-wal` file changes.

use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, LazyLock, Mutex, RwLock, Weak};
use std::time::SystemTime;

use rusqlite::{params, params_from_iter, Connection, ToSql};

use super::journal::{open_existing_read_only, open_journal, UNSTORABLE_ENTRY};
use crate::error::{EngineError, Result};
use crate::pinyin::typos::syllable_typo_kind;
use crate::types::ShuangpinProfileKind;

/// Typo learning describes habits, not dictionary content, so a small bounded table is enough; the rows that matter are the ones seen often (J:728-732).
pub const MAX_TYPO_STATE_ROWS: usize = 2_048;
pub const MAX_TYPO_STATE_COUNT: i32 = 1_000;
pub const MAX_SUPPRESSED_INPUT_LENGTH: usize = 64;
/// The longest quanpin syllable (`zhuang`).
const MAX_SYLLABLE_LENGTH: usize = 6;

#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct PinyinTypoState {
    pub accepted: HashMap<String, HashMap<String, i32>>,
    pub suppressed: HashSet<String>,
    /// 双拼按两键码记的接受和拒绝次数(#10018),只有触屏的触点路径读写。
    pub shuangpin: HashMap<ShuangpinTypoKey, ShuangpinTypoCounts>,
    /// 用户按原样上屏、拒绝过触点纠错的双拼输入,按方案分开。
    pub shuangpin_suppressed: HashMap<ShuangpinProfileKind, HashSet<String>>,
}

/// 双拼的一条纠错:哪个内置方案下,把两键码 `typed` 当成 `intended`。键是小写字母或 `;`。不和全拼共用 `pinyin_typo_counts`:两键码会和全拼音节撞名(`ai`、`an`),`;` 也过不了全拼的校验。
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct ShuangpinTypoKey {
    pub profile: ShuangpinProfileKind,
    pub typed: [u8; 2],
    pub intended: [u8; 2],
}

/// 一条双拼纠错被接受(选中纠错行)和被拒绝(纠错行坐首选、用户却选了别的行)的次数。
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct ShuangpinTypoCounts {
    pub accepted: i32,
    pub rejected: i32,
}

/// 双拼纠错计数的哪一列。
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ShuangpinTypoOutcome {
    Accepted,
    Rejected,
}

impl ShuangpinTypoOutcome {
    fn column(self) -> &'static str {
        match self {
            Self::Accepted => "accepted",
            Self::Rejected => "rejected",
        }
    }
}

/// 只学内置方案:自定义方案的键位随时会改,按旧键位记下的键码对换了键位就是别的意思。
fn learnable_shuangpin_profile(profile: ShuangpinProfileKind) -> bool {
    profile != ShuangpinProfileKind::Custom
}

/// 双拼编码里的一个键:小写字母,或微软双拼的 `;`。
fn is_shuangpin_key(byte: u8) -> bool {
    byte.is_ascii_lowercase() || byte == b';'
}

fn shuangpin_code(text: &str) -> Option<[u8; 2]> {
    let code: [u8; 2] = text.as_bytes().try_into().ok()?;
    code.iter()
        .all(|&byte| is_shuangpin_key(byte))
        .then_some(code)
}

/// 触点纠错只会产出两种改法:换掉一个键,或两键对调。
fn is_shuangpin_one_edit(typed: [u8; 2], intended: [u8; 2]) -> bool {
    let changed = typed
        .iter()
        .zip(&intended)
        .filter(|(left, right)| left != right)
        .count();
    changed == 1 || (changed == 2 && typed == [intended[1], intended[0]])
}

/// 双拼抑制表能存的输入:带触点的输入串,小写字母和 `;`,不含 `'`。
pub fn is_storable_shuangpin_suppression(input: &str) -> bool {
    !input.is_empty()
        && input.len() <= MAX_SUPPRESSED_INPUT_LENGTH
        && input.bytes().all(is_shuangpin_key)
}

fn is_lowercase_letters(text: &str, max_length: usize) -> bool {
    !text.is_empty()
        && text.len() <= max_length
        && text.bytes().all(|byte| byte.is_ascii_lowercase())
}

/// Whether a folded input fits the suppression table (J:864-867); an input that does not is not a write failure to report on every Enter.
pub fn is_storable_autocorrect_suppression(input: &str) -> bool {
    is_lowercase_letters(input, MAX_SUPPRESSED_INPUT_LENGTH)
}

/// Deletes the least used rows, oldest first, until at most `MAX_TYPO_STATE_ROWS` remain. Rows matching `keep` (bound from `?2`) are the ones this transaction just wrote: a new row starts at the lowest count, so without the exclusion a full table would delete it in the same commit that created it (J:746-764).
fn trim_typo_table(
    connection: &Connection,
    table: &str,
    count_column: &str,
    keep: &str,
    keep_values: &[&str],
) -> Result<()> {
    let sql = format!(
        "DELETE FROM {table} WHERE rowid IN (SELECT rowid FROM {table} WHERE NOT ({keep}) ORDER BY {count_column} ASC, updated_at ASC, rowid ASC LIMIT max(0, (SELECT count(*) FROM {table}) - ?1))"
    );
    let limit = MAX_TYPO_STATE_ROWS as i64;
    let mut values: Vec<&dyn ToSql> = vec![&limit];
    values.extend(keep_values.iter().map(|value| value as &dyn ToSql));
    connection
        .prepare(&sql)?
        .execute(params_from_iter(values))?;
    Ok(())
}

/// Increment each accepted `(typed, intended)` pair; the whole batch is refused if any pair is not two different lowercase syllables of at most six letters (J:811-862).
pub fn record_pinyin_typos(user_db: &Path, pairs: &[(String, String)]) -> Result<()> {
    let valid = !pairs.is_empty()
        && pairs.iter().all(|(typed, intended)| {
            is_lowercase_letters(typed, MAX_SYLLABLE_LENGTH)
                && is_lowercase_letters(intended, MAX_SYLLABLE_LENGTH)
                && typed != intended
        });
    if !valid {
        return Err(EngineError::invalid(UNSTORABLE_ENTRY));
    }
    let journal = open_journal(user_db)?;
    journal.execute_batch("BEGIN IMMEDIATE")?;
    {
        let mut upsert = journal.prepare_cached(
            "INSERT INTO pinyin_typo_counts(typed,intended,accepted) VALUES(?1,?2,1) ON CONFLICT(typed,intended) DO UPDATE SET accepted=min(accepted+1,?3),updated_at=unixepoch()",
        )?;
        for (typed, intended) in pairs {
            upsert.execute(params![typed, intended, MAX_TYPO_STATE_COUNT])?;
        }
    }
    // A row-value IN list rather than chained ORs: every OR adds a level of expression depth, and SQLite rejects statements deeper than SQLITE_MAX_EXPR_DEPTH (1000 by default).
    let rows: Vec<String> = (0..pairs.len())
        .map(|index| format!("(?{},?{})", 2 * index + 2, 2 * index + 3))
        .collect();
    let keep = format!("(typed,intended) IN (VALUES {})", rows.join(","));
    let keep_values: Vec<&str> = pairs
        .iter()
        .flat_map(|(typed, intended)| [typed.as_str(), intended.as_str()])
        .collect();
    trim_typo_table(
        &journal,
        "pinyin_typo_counts",
        "accepted",
        &keep,
        &keep_values,
    )?;
    // Any `?` above leaves the transaction to the connection guard's rollback.
    journal.execute_batch("COMMIT")?;
    Ok(())
}

/// J:869-889.
pub fn record_autocorrect_suppression(user_db: &Path, input: &str) -> Result<()> {
    if !is_storable_autocorrect_suppression(input) {
        return Err(EngineError::invalid(UNSTORABLE_ENTRY));
    }
    let journal = open_journal(user_db)?;
    journal.execute_batch("BEGIN IMMEDIATE")?;
    journal
        .prepare_cached(
            "INSERT INTO pinyin_autocorrect_suppressions(input,commits) VALUES(?1,1) ON CONFLICT(input) DO UPDATE SET commits=min(commits+1,?2),updated_at=unixepoch()",
        )?
        .execute(params![input, MAX_TYPO_STATE_COUNT])?;
    trim_typo_table(
        &journal,
        "pinyin_autocorrect_suppressions",
        "commits",
        "input=?2",
        &[input],
    )?;
    journal.execute_batch("COMMIT")?;
    Ok(())
}

/// 每一对加一次 `outcome` 那一列;有一对不是内置方案下合法的一处改动(换一个键或两键对调)就整批拒绝,什么也不写。写完把表修剪到 `MAX_TYPO_STATE_ROWS` 行,先删接受加拒绝最少、最久没动的,这一批写的不删。
pub fn record_shuangpin_typos(
    user_db: &Path,
    profile: ShuangpinProfileKind,
    pairs: &[([u8; 2], [u8; 2])],
    outcome: ShuangpinTypoOutcome,
) -> Result<()> {
    let valid = learnable_shuangpin_profile(profile)
        && !pairs.is_empty()
        && pairs.iter().all(|(typed, intended)| {
            typed
                .iter()
                .chain(intended)
                .all(|&byte| is_shuangpin_key(byte))
                && is_shuangpin_one_edit(*typed, *intended)
        });
    if !valid {
        return Err(EngineError::invalid(UNSTORABLE_ENTRY));
    }
    let codes: Vec<(String, String)> = pairs
        .iter()
        .map(|(typed, intended)| {
            (
                String::from_utf8_lossy(typed).into_owned(),
                String::from_utf8_lossy(intended).into_owned(),
            )
        })
        .collect();
    let column = outcome.column();
    let journal = open_journal(user_db)?;
    journal.execute_batch("BEGIN IMMEDIATE")?;
    {
        let mut upsert = journal.prepare_cached(&format!(
            "INSERT INTO shuangpin_typo_counts(profile,typed,intended,{column}) VALUES(?1,?2,?3,1) ON CONFLICT(profile,typed,intended) DO UPDATE SET {column}=min({column}+1,?4),updated_at=unixepoch()"
        ))?;
        for (typed, intended) in &codes {
            upsert.execute(params![
                profile.name(),
                typed,
                intended,
                MAX_TYPO_STATE_COUNT
            ])?;
        }
    }
    let rows: Vec<String> = (0..codes.len())
        .map(|index| format!("(?2,?{},?{})", 2 * index + 3, 2 * index + 4))
        .collect();
    let keep = format!("(profile,typed,intended) IN (VALUES {})", rows.join(","));
    let mut keep_values: Vec<&str> = vec![profile.name()];
    keep_values.extend(
        codes
            .iter()
            .flat_map(|(typed, intended)| [typed.as_str(), intended.as_str()]),
    );
    trim_typo_table(
        &journal,
        "shuangpin_typo_counts",
        "accepted+rejected",
        &keep,
        &keep_values,
    )?;
    journal.execute_batch("COMMIT")?;
    Ok(())
}

/// 记一次「这串双拼输入有触点纠错可选,用户却按原样上屏」。
pub fn record_shuangpin_suppression(
    user_db: &Path,
    profile: ShuangpinProfileKind,
    input: &str,
) -> Result<()> {
    if !learnable_shuangpin_profile(profile) || !is_storable_shuangpin_suppression(input) {
        return Err(EngineError::invalid(UNSTORABLE_ENTRY));
    }
    let journal = open_journal(user_db)?;
    journal.execute_batch("BEGIN IMMEDIATE")?;
    journal
        .prepare_cached(
            "INSERT INTO shuangpin_autocorrect_suppressions(profile,input,commits) VALUES(?1,?2,1) ON CONFLICT(profile,input) DO UPDATE SET commits=min(commits+1,?3),updated_at=unixepoch()",
        )?
        .execute(params![profile.name(), input, MAX_TYPO_STATE_COUNT])?;
    trim_typo_table(
        &journal,
        "shuangpin_autocorrect_suppressions",
        "commits",
        "profile=?2 AND input=?3",
        &[profile.name(), input],
    )?;
    journal.execute_batch("COMMIT")?;
    Ok(())
}

fn table_exists(connection: &Connection, table: &str) -> Result<bool> {
    Ok(connection
        .prepare_cached("SELECT 1 FROM sqlite_master WHERE type='table' AND name=?1")?
        .exists(params![table])?)
}

/// 一次读日志的结果。
#[derive(Debug, PartialEq, Eq)]
pub struct TypoStateLoad {
    pub state: PinyinTypoState,
    /// 双拼两张表读出来了没有。没读出来(超过行数上限、行的类型不对)时 `state` 的双拼部分为空,全拼部分照样是日志里的内容,由档案决定保留原来的双拼状态。
    pub shuangpin_loaded: bool,
}

/// Read-only; a missing journal or table is an empty state (J:767-809). 全拼两张表读不出来时整次读取失败,和加双拼表之前一样;双拼两张表读不出来不连累全拼,见 [`TypoStateLoad::shuangpin_loaded`]。
pub fn load_pinyin_typo_state(user_db: &Path) -> Result<TypoStateLoad> {
    let mut state = PinyinTypoState::default();
    let Some(connection) = open_existing_read_only(user_db)? else {
        return Ok(TypoStateLoad {
            state,
            shuangpin_loaded: true,
        });
    };
    if table_exists(&connection, "pinyin_typo_counts")? {
        let count: i64 = connection.query_row(
            "SELECT count(*) FROM pinyin_typo_counts WHERE accepted > 0 AND accepted <= ?1 AND length(CAST(typed AS BLOB)) BETWEEN 1 AND ?2 AND length(CAST(intended AS BLOB)) BETWEEN 1 AND ?2",
            params![MAX_TYPO_STATE_COUNT, MAX_SYLLABLE_LENGTH as i64],
            |row| row.get(0),
        )?;
        if count > MAX_TYPO_STATE_ROWS as i64 {
            return Err(EngineError::failed(
                "pinyin typo state exceeds its memory limit",
            ));
        }
        let mut statement = connection
            .prepare("SELECT typed,intended,accepted FROM pinyin_typo_counts WHERE accepted > 0 AND accepted <= ?1 AND length(CAST(typed AS BLOB)) BETWEEN 1 AND ?2 AND length(CAST(intended AS BLOB)) BETWEEN 1 AND ?2")?;
        let rows = statement.query_map(
            params![MAX_TYPO_STATE_COUNT, MAX_SYLLABLE_LENGTH as i64],
            |row| {
                Ok((
                    row.get::<_, String>(0)?,
                    row.get::<_, String>(1)?,
                    row.get::<_, i32>(2)?,
                ))
            },
        )?;
        for row in rows {
            let (typed, intended, accepted) = row?;
            if is_lowercase_letters(&typed, MAX_SYLLABLE_LENGTH)
                && is_lowercase_letters(&intended, MAX_SYLLABLE_LENGTH)
                && typed != intended
            {
                state
                    .accepted
                    .entry(typed)
                    .or_default()
                    .insert(intended, accepted);
            }
        }
    }
    if table_exists(&connection, "pinyin_autocorrect_suppressions")? {
        let count: i64 = connection.query_row(
            "SELECT count(*) FROM pinyin_autocorrect_suppressions WHERE commits >= 1 AND length(CAST(input AS BLOB)) BETWEEN 1 AND ?1",
            params![MAX_SUPPRESSED_INPUT_LENGTH as i64],
            |row| row.get(0),
        )?;
        if count > MAX_TYPO_STATE_ROWS as i64 {
            return Err(EngineError::failed(
                "pinyin suppression state exceeds its memory limit",
            ));
        }
        let mut statement =
            connection.prepare("SELECT input FROM pinyin_autocorrect_suppressions WHERE commits >= 1 AND length(CAST(input AS BLOB)) BETWEEN 1 AND ?1")?;
        let rows = statement.query_map(params![MAX_SUPPRESSED_INPUT_LENGTH as i64], |row| {
            row.get::<_, String>(0)
        })?;
        for row in rows {
            let input = row?;
            if is_lowercase_letters(&input, MAX_SUPPRESSED_INPUT_LENGTH) {
                state.suppressed.insert(input);
            }
        }
    }
    // 双拼先读进一份空状态,读到一半失败时不留下半截的双拼数据。
    let mut shuangpin = PinyinTypoState::default();
    let shuangpin_loaded = load_shuangpin_typo_state(&connection, &mut shuangpin).is_ok();
    if shuangpin_loaded {
        state.shuangpin = shuangpin.shuangpin;
        state.shuangpin_suppressed = shuangpin.shuangpin_suppressed;
    }
    Ok(TypoStateLoad {
        state,
        shuangpin_loaded,
    })
}

/// 两张双拼表读进 `state`;没有这两张表的旧日志读作空。行数超过上限或有一行类型不对时返回错误,只作废双拼这一部分。
fn load_shuangpin_typo_state(connection: &Connection, state: &mut PinyinTypoState) -> Result<()> {
    const COUNTS_FILTER: &str = "FROM shuangpin_typo_counts WHERE accepted BETWEEN 0 AND ?1 AND rejected BETWEEN 0 AND ?1 AND accepted+rejected > 0 AND length(CAST(typed AS BLOB))=2 AND length(CAST(intended AS BLOB))=2";
    if table_exists(connection, "shuangpin_typo_counts")? {
        let count: i64 = connection.query_row(
            &format!("SELECT count(*) {COUNTS_FILTER}"),
            params![MAX_TYPO_STATE_COUNT],
            |row| row.get(0),
        )?;
        if count > MAX_TYPO_STATE_ROWS as i64 {
            return Err(EngineError::failed(
                "shuangpin typo state exceeds its memory limit",
            ));
        }
        let mut statement = connection.prepare(&format!(
            "SELECT profile,typed,intended,accepted,rejected {COUNTS_FILTER}"
        ))?;
        let rows = statement.query_map(params![MAX_TYPO_STATE_COUNT], |row| {
            Ok((
                row.get::<_, String>(0)?,
                row.get::<_, String>(1)?,
                row.get::<_, String>(2)?,
                row.get::<_, i32>(3)?,
                row.get::<_, i32>(4)?,
            ))
        })?;
        for row in rows {
            let (profile, typed, intended, accepted, rejected) = row?;
            let key = ShuangpinProfileKind::from_name(&profile)
                .filter(|profile| learnable_shuangpin_profile(*profile))
                .zip(shuangpin_code(&typed).zip(shuangpin_code(&intended)))
                .filter(|(_, (typed, intended))| is_shuangpin_one_edit(*typed, *intended));
            if let Some((profile, (typed, intended))) = key {
                state.shuangpin.insert(
                    ShuangpinTypoKey {
                        profile,
                        typed,
                        intended,
                    },
                    ShuangpinTypoCounts { accepted, rejected },
                );
            }
        }
    }
    if table_exists(connection, "shuangpin_autocorrect_suppressions")? {
        const FILTER: &str = "FROM shuangpin_autocorrect_suppressions WHERE commits >= 1 AND length(CAST(input AS BLOB)) BETWEEN 1 AND ?1";
        let count: i64 = connection.query_row(
            &format!("SELECT count(*) {FILTER}"),
            params![MAX_SUPPRESSED_INPUT_LENGTH as i64],
            |row| row.get(0),
        )?;
        if count > MAX_TYPO_STATE_ROWS as i64 {
            return Err(EngineError::failed(
                "shuangpin suppression state exceeds its memory limit",
            ));
        }
        let mut statement = connection.prepare(&format!("SELECT profile,input {FILTER}"))?;
        let rows = statement.query_map(params![MAX_SUPPRESSED_INPUT_LENGTH as i64], |row| {
            Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?))
        })?;
        for row in rows {
            let (profile, input) = row?;
            let profile = ShuangpinProfileKind::from_name(&profile)
                .filter(|profile| learnable_shuangpin_profile(*profile));
            if let Some(profile) = profile.filter(|_| is_storable_shuangpin_suppression(&input)) {
                state
                    .shuangpin_suppressed
                    .entry(profile)
                    .or_default()
                    .insert(input);
            }
        }
    }
    Ok(())
}

/// `(modified, size)` of a file, `None` when it cannot be read; the journal and its `-wal` together say whether anything was written since the last load.
type FileStamp = Option<(SystemTime, u64)>;

fn file_stamp(path: &Path) -> FileStamp {
    let metadata = std::fs::metadata(path).ok()?;
    Some((metadata.modified().ok()?, metadata.len()))
}

/// Profiles are shared weakly: one per journal while any engine holds it (TP:22-51).
static PROFILES: LazyLock<Mutex<HashMap<PathBuf, Weak<PersonalTypoProfile>>>> =
    LazyLock::new(|| Mutex::new(HashMap::new()));

pub struct PersonalTypoProfile {
    state: std::sync::RwLock<PinyinTypoState>,
    path: PathBuf,
    wal: PathBuf,
    /// Serialises loads and writes; holds the stamp of the files the state was last loaded from, `None` before the first successful load.
    loaded: Mutex<Option<(FileStamp, FileStamp)>>,
    generation: AtomicU64,
}

impl PersonalTypoProfile {
    /// One profile per journal path for the process.
    pub fn shared(user_db: &Path) -> Arc<PersonalTypoProfile> {
        let profile = {
            let mut profiles = PROFILES
                .lock()
                .unwrap_or_else(|poisoned| poisoned.into_inner());
            if let Some(profile) = profiles.get(user_db).and_then(Weak::upgrade) {
                return profile;
            }
            let mut wal = user_db.as_os_str().to_owned();
            wal.push("-wal");
            let profile = Arc::new(PersonalTypoProfile {
                state: RwLock::new(PinyinTypoState::default()),
                path: user_db.to_path_buf(),
                wal: PathBuf::from(wal),
                loaded: Mutex::new(None),
                generation: AtomicU64::new(0),
            });
            profiles.retain(|_, weak| weak.strong_count() > 0);
            profiles.insert(user_db.to_path_buf(), Arc::downgrade(&profile));
            profile
        };
        // A new profile loads here, while the session is being created, rather than on its first keystroke.
        profile.refresh_if_changed();
        profile
    }

    fn stamp(&self) -> (FileStamp, FileStamp) {
        (file_stamp(&self.path), file_stamp(&self.wal))
    }

    fn replace(&self, state: PinyinTypoState) {
        *self
            .state
            .write()
            .unwrap_or_else(|poisoned| poisoned.into_inner()) = state;
        self.generation.fetch_add(1, Ordering::AcqRel);
    }

    /// Adopt a freshly loaded state; the generation only moves when the contents did.
    fn adopt(&self, state: PinyinTypoState) {
        let unchanged = *self
            .state
            .read()
            .unwrap_or_else(|poisoned| poisoned.into_inner())
            == state;
        if !unchanged {
            self.replace(state);
        }
    }

    /// Reload when the journal's or its `-wal`'s (mtime, size) moved; the generation advances on every reload.
    pub fn refresh_if_changed(&self) {
        let mut loaded = self
            .loaded
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        let stamp = self.stamp();
        if loaded.as_ref() == Some(&stamp) {
            return;
        }
        // A journal that exists but cannot be read keeps the held state; the unchanged stamp retries on the next query (TP:115-116).
        let Ok(load) = load_pinyin_typo_state(&self.path) else {
            return;
        };
        if load.shuangpin_loaded {
            *loaded = Some(stamp);
            self.adopt(load.state);
        } else {
            // 只有双拼两张表读不出来:全拼照样跟上日志,双拼保留原来的状态;不记下这次的文件戳,下次查询再试双拼。
            let state = self.with_held_shuangpin(load.state, |_| {});
            self.adopt(state);
        }
    }

    /// 日志里新读出的全拼部分,配上档案原来持有的双拼部分,再套上 `patch`。全拼部分在 `patch` 之后才换上,所以全拼的写入不会在读回的计数上再加一次。
    fn with_held_shuangpin(
        &self,
        fresh: PinyinTypoState,
        patch: impl FnOnce(&mut PinyinTypoState),
    ) -> PinyinTypoState {
        let mut state = self
            .state
            .read()
            .unwrap_or_else(|poisoned| poisoned.into_inner())
            .clone();
        patch(&mut state);
        state.accepted = fresh.accepted;
        state.suppressed = fresh.suppressed;
        state
    }

    pub fn generation(&self) -> u64 {
        self.generation.load(Ordering::Acquire)
    }

    pub fn accepted(&self, typed: &str, intended: &str) -> i32 {
        let state = self
            .state
            .read()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        state
            .accepted
            .get(typed)
            .and_then(|by_intended| by_intended.get(intended))
            .copied()
            .unwrap_or(0)
    }

    pub fn suppressed(&self, input_key: &str) -> bool {
        let state = self
            .state
            .read()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        !state.suppressed.is_empty() && state.suppressed.contains(input_key)
    }

    /// After this profile's own write: read the journal back, or when that fails apply the write to the held state so the session sees it at once (TP:78-91).
    fn reload_after_write(
        &self,
        loaded: &mut Option<(FileStamp, FileStamp)>,
        patch: impl FnOnce(&mut PinyinTypoState),
    ) {
        let stamp = self.stamp();
        match load_pinyin_typo_state(&self.path) {
            Ok(load) if load.shuangpin_loaded => {
                *loaded = Some(stamp);
                self.adopt(load.state);
            }
            // 双拼两张表读不出来:全拼用读回的,双拼在原来的状态上补上这次写入。
            Ok(load) => {
                let state = self.with_held_shuangpin(load.state, patch);
                self.replace(state);
            }
            Err(_) => {
                let mut state = self
                    .state
                    .read()
                    .unwrap_or_else(|poisoned| poisoned.into_inner())
                    .clone();
                patch(&mut state);
                self.replace(state);
            }
        }
    }

    /// Write and reload. Every pair must be a known one-edit typo (TP:132-151).
    pub fn record_accepted(&self, pairs: &[(String, String)]) -> Result<()> {
        if pairs
            .iter()
            .any(|(typed, intended)| syllable_typo_kind(typed, intended).is_none())
        {
            return Err(EngineError::invalid(UNSTORABLE_ENTRY));
        }
        let mut loaded = self
            .loaded
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        record_pinyin_typos(&self.path, pairs)?;
        self.reload_after_write(&mut loaded, |state| {
            for pair in pairs {
                let count = state
                    .accepted
                    .entry(pair.0.clone())
                    .or_default()
                    .entry(pair.1.clone())
                    .or_insert(0);
                *count = (*count + 1).min(MAX_TYPO_STATE_COUNT);
            }
        });
        Ok(())
    }

    pub fn record_suppression(&self, input_key: &str) -> Result<()> {
        let mut loaded = self
            .loaded
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        record_autocorrect_suppression(&self.path, input_key)?;
        self.reload_after_write(&mut loaded, |state| {
            state.suppressed.insert(input_key.to_owned());
        });
        Ok(())
    }

    /// 有没有任何双拼纠错计数:没有时计价不必逐个变体去查。
    pub fn has_shuangpin_counts(&self) -> bool {
        !self
            .state
            .read()
            .unwrap_or_else(|poisoned| poisoned.into_inner())
            .shuangpin
            .is_empty()
    }

    /// 双拼方案 `profile` 下把 `typed` 当成 `intended` 的接受和拒绝次数;没记过时都是 0。不分配。
    pub fn shuangpin_counts(
        &self,
        profile: ShuangpinProfileKind,
        typed: [u8; 2],
        intended: [u8; 2],
    ) -> ShuangpinTypoCounts {
        let state = self
            .state
            .read()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        if state.shuangpin.is_empty() {
            return ShuangpinTypoCounts::default();
        }
        state
            .shuangpin
            .get(&ShuangpinTypoKey {
                profile,
                typed,
                intended,
            })
            .copied()
            .unwrap_or_default()
    }

    /// 这串双拼输入在方案 `profile` 下是否被用户拒绝过触点纠错。
    pub fn shuangpin_suppressed(&self, profile: ShuangpinProfileKind, input: &str) -> bool {
        let state = self
            .state
            .read()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        state
            .shuangpin_suppressed
            .get(&profile)
            .is_some_and(|inputs| inputs.contains(input))
    }

    /// 写一批双拼纠错的接受或拒绝并重读,规则见 [`record_shuangpin_typos`]。
    pub fn record_shuangpin(
        &self,
        profile: ShuangpinProfileKind,
        pairs: &[([u8; 2], [u8; 2])],
        outcome: ShuangpinTypoOutcome,
    ) -> Result<()> {
        let mut loaded = self
            .loaded
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        record_shuangpin_typos(&self.path, profile, pairs, outcome)?;
        self.reload_after_write(&mut loaded, |state| {
            for &(typed, intended) in pairs {
                let counts = state
                    .shuangpin
                    .entry(ShuangpinTypoKey {
                        profile,
                        typed,
                        intended,
                    })
                    .or_default();
                let count = match outcome {
                    ShuangpinTypoOutcome::Accepted => &mut counts.accepted,
                    ShuangpinTypoOutcome::Rejected => &mut counts.rejected,
                };
                *count = (*count + 1).min(MAX_TYPO_STATE_COUNT);
            }
        });
        Ok(())
    }

    /// 记下双拼输入 `input` 被拒绝了触点纠错并重读。
    pub fn record_shuangpin_suppression(
        &self,
        profile: ShuangpinProfileKind,
        input: &str,
    ) -> Result<()> {
        let mut loaded = self
            .loaded
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        record_shuangpin_suppression(&self.path, profile, input)?;
        self.reload_after_write(&mut loaded, |state| {
            state
                .shuangpin_suppressed
                .entry(profile)
                .or_default()
                .insert(input.to_owned());
        });
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::super::journal::test_support::{count, Dir};
    use super::*;

    fn pair(typed: &str, intended: &str) -> (String, String) {
        (typed.to_owned(), intended.to_owned())
    }

    fn typo_count(journal: &Path, typed: &str, intended: &str) -> i64 {
        count(
            journal,
            &format!("SELECT accepted FROM pinyin_typo_counts WHERE typed='{typed}' AND intended='{intended}'"),
        )
    }

    #[test]
    fn accepted_lookup_borrows_both_syllables_without_allocating() {
        let dir = Dir::new();
        let profile = PersonalTypoProfile::shared(&dir.journal());
        profile.record_accepted(&[pair("gan", "guan")]).unwrap();

        let (values, allocations) = crate::ime::personal_rerank::allocations::count(|| {
            (
                profile.accepted("gan", "guan"),
                profile.accepted("sahng", "shang"),
            )
        });

        assert_eq!(values, (1, 0));
        assert_eq!(allocations, 0);
    }

    /// test_typo_correction_input_session.cpp:345-378.
    #[test]
    fn batches_are_validated_and_tables_are_capped() {
        let dir = Dir::new();
        let journal = dir.journal();
        assert!(record_pinyin_typos(&journal, &[pair("gan", "guan"), pair("", "x")]).is_err());
        assert!(record_pinyin_typos(&journal, &[pair("gan", "gan")]).is_err());
        assert!(record_pinyin_typos(&journal, &[pair("zhuangg", "zhuang")]).is_err());
        assert!(record_pinyin_typos(&journal, &[]).is_err());
        assert!(!journal.exists(), "a rejected batch opened the journal");
        assert!(record_autocorrect_suppression(&journal, "Sa'hng").is_err());

        record_pinyin_typos(&journal, &[pair("gan", "guan")]).unwrap();
        let rows: Vec<String> = (0..2100)
            .map(|i: usize| {
                let code: String = (0..3)
                    .map(|digit| (b'a' + (i / 26usize.pow(digit) % 26) as u8) as char)
                    .collect();
                format!("('{code}','{code}z',1)")
            })
            .collect();
        Connection::open(&journal)
            .unwrap()
            .execute_batch(&format!(
                "INSERT INTO pinyin_typo_counts(typed,intended,accepted) VALUES{};",
                rows.join(",")
            ))
            .unwrap();
        record_pinyin_typos(&journal, &[pair("sahng", "shang"), pair("gan", "guan")]).unwrap();
        assert_eq!(
            count(&journal, "SELECT count(*) FROM pinyin_typo_counts"),
            2048
        );
        assert_eq!(typo_count(&journal, "sahng", "shang"), 1);
        assert_eq!(typo_count(&journal, "gan", "guan"), 2);

        let inputs: Vec<String> = (0..2100).map(|i| format!("('input{i}',1)")).collect();
        Connection::open(&journal)
            .unwrap()
            .execute_batch(&format!(
                "INSERT INTO pinyin_autocorrect_suppressions(input,commits) VALUES{};",
                inputs.join(",")
            ))
            .unwrap();
        record_autocorrect_suppression(&journal, "shabg").unwrap();
        assert_eq!(
            count(
                &journal,
                "SELECT count(*) FROM pinyin_autocorrect_suppressions"
            ),
            2048
        );
        assert_eq!(
            count(
                &journal,
                "SELECT count(*) FROM pinyin_autocorrect_suppressions WHERE input='shabg'"
            ),
            1
        );
    }

    #[test]
    fn counts_saturate_at_the_cap() {
        let dir = Dir::new();
        let journal = dir.journal();
        record_pinyin_typos(&journal, &[pair("gan", "guan")]).unwrap();
        Connection::open(&journal)
            .unwrap()
            .execute_batch("UPDATE pinyin_typo_counts SET accepted=1000")
            .unwrap();
        record_pinyin_typos(&journal, &[pair("gan", "guan")]).unwrap();
        assert_eq!(typo_count(&journal, "gan", "guan"), 1000);
    }

    #[test]
    fn loading_a_typo_table_over_the_memory_cap_fails_closed() {
        let dir = Dir::new();
        let journal = dir.journal();
        record_pinyin_typos(&journal, &[pair("gan", "guan")]).unwrap();
        let connection = Connection::open(&journal).unwrap();
        for index in 0..=MAX_TYPO_STATE_ROWS {
            let typed = format!("a{:02}", index % 100);
            let intended = format!("b{:02}", index / 100);
            connection
                .execute(
                    "INSERT INTO pinyin_typo_counts(typed,intended,accepted) VALUES(?1,?2,1)",
                    (&typed, &intended),
                )
                .unwrap();
        }

        assert!(load_pinyin_typo_state(&journal).is_err());
    }

    #[test]
    fn loading_a_suppression_table_over_the_memory_cap_fails_closed() {
        let dir = Dir::new();
        let journal = dir.journal();
        record_autocorrect_suppression(&journal, "shabg").unwrap();
        let connection = Connection::open(&journal).unwrap();
        for index in 0..=MAX_TYPO_STATE_ROWS {
            let input = format!("input{index}");
            connection
                .execute(
                    "INSERT INTO pinyin_autocorrect_suppressions(input,commits) VALUES(?1,1)",
                    [&input],
                )
                .unwrap();
        }

        assert!(load_pinyin_typo_state(&journal).is_err());
    }

    #[test]
    fn a_missing_or_old_journal_reads_as_empty() {
        let dir = Dir::new();
        let nowhere = dir.root.path().join("nowhere").join("msime_user.db");
        let empty = TypoStateLoad {
            state: PinyinTypoState::default(),
            shuangpin_loaded: true,
        };
        assert_eq!(load_pinyin_typo_state(&nowhere).unwrap(), empty);
        assert!(!dir.root.path().join("nowhere").exists());

        let legacy = dir.journal();
        Connection::open(&legacy)
            .unwrap()
            .execute_batch("CREATE TABLE user_dictionary_operations(dictionary TEXT NOT NULL,key TEXT NOT NULL,value TEXT NOT NULL,operation TEXT NOT NULL,PRIMARY KEY(dictionary,key,value));PRAGMA user_version=3;")
            .unwrap();
        assert_eq!(load_pinyin_typo_state(&legacy).unwrap(), empty);
        assert_eq!(
            count(&legacy, "PRAGMA user_version"),
            3,
            "a read upgraded the journal"
        );
    }

    #[test]
    fn the_profile_sees_its_own_writes_and_other_writers() {
        let dir = Dir::new();
        let journal = dir.journal();
        let profile = PersonalTypoProfile::shared(&journal);
        assert!(Arc::ptr_eq(
            &profile,
            &PersonalTypoProfile::shared(&journal)
        ));
        assert_eq!(profile.accepted("gan", "guan"), 0);
        let before = profile.generation();

        assert!(profile.record_accepted(&[pair("gan", "zzz")]).is_err());
        profile.record_accepted(&[pair("gan", "guan")]).unwrap();
        assert_eq!(profile.accepted("gan", "guan"), 1);
        assert!(profile.generation() > before);

        profile.record_suppression("shabg").unwrap();
        assert!(profile.suppressed("shabg"));
        assert!(!profile.suppressed("shang"));

        // Another writer on the same file is seen once the stamp moves.
        let generation = profile.generation();
        record_autocorrect_suppression(&journal, "sahng").unwrap();
        // A one-row write may leave the size alone and land within the file system's time granularity, so the stamp is moved on purpose.
        std::fs::File::options()
            .write(true)
            .open(&journal)
            .unwrap()
            .set_modified(SystemTime::now() + std::time::Duration::from_secs(2))
            .unwrap();
        profile.refresh_if_changed();
        assert!(profile.suppressed("sahng"));
        assert!(profile.generation() > generation);

        // An unchanged file costs a stat and keeps the generation.
        let generation = profile.generation();
        profile.refresh_if_changed();
        assert_eq!(profile.generation(), generation);
    }

    // ---- 双拼按两键码学的纠错(#10018) ----

    const XIAOHE: ShuangpinProfileKind = ShuangpinProfileKind::Xiaohe;

    fn shuangpin_count(
        journal: &Path,
        column: &str,
        profile: &str,
        typed: &str,
        intended: &str,
    ) -> i64 {
        count(
            journal,
            &format!("SELECT {column} FROM shuangpin_typo_counts WHERE profile='{profile}' AND typed='{typed}' AND intended='{intended}'"),
        )
    }

    /// 整批校验:内置方案、两个键都是小写字母或 `;`、只换一个键或两键对调,有一对不合格就什么也不写,连日志都不开。接受和拒绝各记各的列,满 1000 不再涨。
    #[test]
    fn shuangpin_batches_are_validated_and_counted_per_outcome() {
        let dir = Dir::new();
        let journal = dir.journal();
        let accepted = ShuangpinTypoOutcome::Accepted;
        for (profile, pairs) in [
            (ShuangpinProfileKind::Custom, vec![(*b"gf", *b"gr")]),
            (XIAOHE, vec![]),
            (XIAOHE, vec![(*b"gf", *b"gf")]),
            (XIAOHE, vec![(*b"gf", *b"hr")]),
            (XIAOHE, vec![(*b"gf", *b"gR")]),
            (XIAOHE, vec![(*b"g'", *b"gr")]),
            (XIAOHE, vec![(*b"gf", *b"gr"), (*b"ab", *b"cd")]),
        ] {
            assert!(
                record_shuangpin_typos(&journal, profile, &pairs, accepted).is_err(),
                "{pairs:?}"
            );
        }
        assert!(
            record_shuangpin_suppression(&journal, ShuangpinProfileKind::Custom, "mwgfxi").is_err()
        );
        for input in ["", "mw'gf", "mwGf", "啊"] {
            assert!(
                record_shuangpin_suppression(&journal, XIAOHE, input).is_err(),
                "{input}"
            );
        }
        assert!(!journal.exists(), "a rejected batch opened the journal");

        record_shuangpin_typos(
            &journal,
            XIAOHE,
            &[(*b"gf", *b"gr"), (*b"j;", *b";j")],
            accepted,
        )
        .unwrap();
        record_shuangpin_typos(&journal, XIAOHE, &[(*b"gf", *b"gr")], accepted).unwrap();
        record_shuangpin_typos(
            &journal,
            XIAOHE,
            &[(*b"gf", *b"gr")],
            ShuangpinTypoOutcome::Rejected,
        )
        .unwrap();
        record_shuangpin_typos(
            &journal,
            ShuangpinProfileKind::Microsoft,
            &[(*b"gf", *b"gr")],
            accepted,
        )
        .unwrap();
        assert_eq!(
            shuangpin_count(&journal, "accepted", "xiaohe", "gf", "gr"),
            2
        );
        assert_eq!(
            shuangpin_count(&journal, "rejected", "xiaohe", "gf", "gr"),
            1
        );
        assert_eq!(
            shuangpin_count(&journal, "accepted", "xiaohe", "j;", ";j"),
            1
        );
        assert_eq!(
            shuangpin_count(&journal, "rejected", "xiaohe", "j;", ";j"),
            0
        );
        assert_eq!(
            shuangpin_count(&journal, "accepted", "microsoft", "gf", "gr"),
            1
        );
        // 双拼不碰全拼的表。
        assert_eq!(
            count(&journal, "SELECT count(*) FROM pinyin_typo_counts"),
            0
        );

        Connection::open(&journal)
            .unwrap()
            .execute_batch("UPDATE shuangpin_typo_counts SET accepted=1000")
            .unwrap();
        record_shuangpin_typos(&journal, XIAOHE, &[(*b"gf", *b"gr")], accepted).unwrap();
        assert_eq!(
            shuangpin_count(&journal, "accepted", "xiaohe", "gf", "gr"),
            1000
        );

        record_shuangpin_suppression(&journal, XIAOHE, "mwgfxi").unwrap();
        record_shuangpin_suppression(&journal, XIAOHE, "mwgfxi").unwrap();
        record_shuangpin_suppression(&journal, ShuangpinProfileKind::Ziranma, "mwgfxi").unwrap();
        assert_eq!(
            count(&journal, "SELECT commits FROM shuangpin_autocorrect_suppressions WHERE profile='xiaohe' AND input='mwgfxi'"),
            2
        );
        assert_eq!(
            count(
                &journal,
                "SELECT count(*) FROM pinyin_autocorrect_suppressions"
            ),
            0
        );
    }

    /// 两张表都修剪到 `MAX_TYPO_STATE_ROWS` 行:先删接受加拒绝(或上屏次数)最少、最久没动的,这一批刚写的不删。
    #[test]
    fn shuangpin_tables_are_pruned_to_the_cap() {
        let dir = Dir::new();
        let journal = dir.journal();
        let accepted = ShuangpinTypoOutcome::Accepted;
        record_shuangpin_typos(&journal, XIAOHE, &[(*b"gf", *b"gr")], accepted).unwrap();
        record_shuangpin_typos(
            &journal,
            XIAOHE,
            &[(*b"gf", *b"gr")],
            ShuangpinTypoOutcome::Rejected,
        )
        .unwrap();
        let connection = Connection::open(&journal).unwrap();
        connection
            .execute_batch(
                "WITH RECURSIVE n(i) AS (SELECT 0 UNION ALL SELECT i+1 FROM n WHERE i<2099) INSERT INTO shuangpin_typo_counts(profile,typed,intended,accepted,updated_at) SELECT 'ziranma',char(97+i%26)||char(97+(i/26)%26),char(97+i%26)||char(97+(i/676)%26+1),1,i FROM n;",
            )
            .unwrap();
        record_shuangpin_typos(&journal, XIAOHE, &[(*b"hc", *b"hv")], accepted).unwrap();
        assert_eq!(
            count(&journal, "SELECT count(*) FROM shuangpin_typo_counts"),
            2048
        );
        assert_eq!(
            shuangpin_count(&journal, "accepted", "xiaohe", "hc", "hv"),
            1
        );
        // 接受加拒绝是 2 的那一行比只记过 1 次的留得久。
        assert_eq!(
            shuangpin_count(&journal, "accepted", "xiaohe", "gf", "gr"),
            1
        );

        connection
            .execute_batch(
                "WITH RECURSIVE n(i) AS (SELECT 0 UNION ALL SELECT i+1 FROM n WHERE i<2099) INSERT INTO shuangpin_autocorrect_suppressions(profile,input,commits,updated_at) SELECT 'xiaohe','a'||i,1,i FROM n;",
            )
            .unwrap();
        record_shuangpin_suppression(&journal, XIAOHE, "mwgfxi").unwrap();
        assert_eq!(
            count(
                &journal,
                "SELECT count(*) FROM shuangpin_autocorrect_suppressions"
            ),
            2048
        );
        assert_eq!(
            count(
                &journal,
                "SELECT count(*) FROM shuangpin_autocorrect_suppressions WHERE input='mwgfxi'"
            ),
            1
        );
    }

    #[test]
    fn loading_a_shuangpin_table_over_the_memory_cap_fails_closed() {
        for table in [
            "shuangpin_typo_counts",
            "shuangpin_autocorrect_suppressions",
        ] {
            let dir = Dir::new();
            let journal = dir.journal();
            record_shuangpin_suppression(&journal, XIAOHE, "mwgfxi").unwrap();
            let rows = if table == "shuangpin_typo_counts" {
                "INSERT INTO shuangpin_typo_counts(profile,typed,intended,accepted) SELECT 'xiaohe',char(97+i%26)||char(97+(i/26)%26),char(97+i%26)||char(97+(i/676)%26+1),1 FROM n;"
            } else {
                "INSERT INTO shuangpin_autocorrect_suppressions(profile,input,commits) SELECT 'xiaohe','a'||i,1 FROM n;"
            };
            Connection::open(&journal)
                .unwrap()
                .execute_batch(&format!(
                    "WITH RECURSIVE n(i) AS (SELECT 0 UNION ALL SELECT i+1 FROM n WHERE i<{MAX_TYPO_STATE_ROWS}) {rows}"
                ))
                .unwrap();
            let load = load_pinyin_typo_state(&journal).unwrap();
            assert!(!load.shuangpin_loaded, "{table}");
            assert!(
                load.state.shuangpin.is_empty() && load.state.shuangpin_suppressed.is_empty(),
                "{table}"
            );
        }
    }

    /// 双拼两张表读不出来(超过行数上限、有一行类型不对)时,全拼两张表照样读出来:全拼学习不受双拼表连累。
    #[test]
    fn a_broken_shuangpin_table_leaves_the_quanpin_load_alone() {
        for breakage in [
            "INSERT INTO shuangpin_typo_counts(profile,typed,intended,accepted) SELECT 'xiaohe',char(97+i%26)||char(97+(i/26)%26),char(97+i%26)||char(97+(i/676)%26+1),1 FROM n;",
            "INSERT INTO shuangpin_autocorrect_suppressions(profile,input,commits) SELECT 'xiaohe','a'||i,1 FROM n;",
            "INSERT INTO shuangpin_typo_counts(profile,typed,intended,accepted) VALUES('xiaohe','ab','ac',2.5);",
            "INSERT INTO shuangpin_typo_counts(profile,typed,intended,accepted) VALUES('xiaohe',X'6162','ac',1);",
            "INSERT INTO shuangpin_autocorrect_suppressions(profile,input,commits) VALUES('xiaohe',X'6162',1);",
        ] {
            let dir = Dir::new();
            let journal = dir.journal();
            record_pinyin_typos(&journal, &[pair("gan", "guan")]).unwrap();
            record_autocorrect_suppression(&journal, "shabg").unwrap();
            record_shuangpin_suppression(&journal, XIAOHE, "mwgfxi").unwrap();
            Connection::open(&journal)
                .unwrap()
                .execute_batch(&format!(
                    "WITH RECURSIVE n(i) AS (SELECT 0 UNION ALL SELECT i+1 FROM n WHERE i<{MAX_TYPO_STATE_ROWS}) {breakage}"
                ))
                .unwrap();
            let load = load_pinyin_typo_state(&journal).unwrap();
            assert!(!load.shuangpin_loaded, "{breakage}");
            assert_eq!(
                load.state.accepted,
                HashMap::from([(
                    "gan".to_owned(),
                    HashMap::from([("guan".to_owned(), 1)])
                )]),
                "{breakage}"
            );
            assert_eq!(
                load.state.suppressed,
                HashSet::from(["shabg".to_owned()]),
                "{breakage}"
            );
        }
    }

    /// 双拼表坏了的时候,档案的全拼部分照样跟上别的写入方和自己的写入(自己的写入只算一次),双拼部分保留原来的状态并补上自己的写入;表修好后双拼部分重新按日志读。
    #[test]
    fn a_broken_shuangpin_table_keeps_the_held_shuangpin_state_and_follows_quanpin() {
        let dir = Dir::new();
        let journal = dir.journal();
        let profile = PersonalTypoProfile::shared(&journal);
        let accepted = ShuangpinTypoOutcome::Accepted;
        profile
            .record_shuangpin(XIAOHE, &[(*b"gf", *b"gr")], accepted)
            .unwrap();
        profile
            .record_shuangpin_suppression(XIAOHE, "mwgfxi")
            .unwrap();
        let bump = || {
            std::fs::File::options()
                .write(true)
                .open(&journal)
                .unwrap()
                .set_modified(SystemTime::now() + std::time::Duration::from_secs(2))
                .unwrap();
        };

        Connection::open(&journal)
            .unwrap()
            .execute_batch("INSERT INTO shuangpin_typo_counts(profile,typed,intended,accepted) VALUES('xiaohe','ab','ac',2.5)")
            .unwrap();
        record_pinyin_typos(&journal, &[pair("gan", "guan")]).unwrap();
        bump();
        profile.refresh_if_changed();
        assert_eq!(profile.accepted("gan", "guan"), 1);
        assert_eq!(profile.shuangpin_counts(XIAOHE, *b"gf", *b"gr").accepted, 1);
        assert!(profile.shuangpin_suppressed(XIAOHE, "mwgfxi"));

        profile.record_accepted(&[pair("gan", "guan")]).unwrap();
        assert_eq!(profile.accepted("gan", "guan"), 2);
        profile.record_suppression("shabg").unwrap();
        assert!(profile.suppressed("shabg"));
        profile
            .record_shuangpin(XIAOHE, &[(*b"gf", *b"gr")], accepted)
            .unwrap();
        assert_eq!(profile.shuangpin_counts(XIAOHE, *b"gf", *b"gr").accepted, 2);
        profile
            .record_shuangpin_suppression(XIAOHE, "gfxi")
            .unwrap();
        assert!(profile.shuangpin_suppressed(XIAOHE, "gfxi"));
        assert_eq!(profile.accepted("gan", "guan"), 2);

        // 全拼的重置由别的写入方做,档案照样跟上。
        Connection::open(&journal)
            .unwrap()
            .execute_batch("DELETE FROM pinyin_typo_counts")
            .unwrap();
        bump();
        profile.refresh_if_changed();
        assert_eq!(profile.accepted("gan", "guan"), 0);
        assert_eq!(profile.shuangpin_counts(XIAOHE, *b"gf", *b"gr").accepted, 2);

        // 修好坏行,双拼部分重新按日志读:日志里没有的 ab→ac 不会出现,自己写过的计数还在。
        Connection::open(&journal)
            .unwrap()
            .execute_batch("DELETE FROM shuangpin_typo_counts WHERE typed='ab'")
            .unwrap();
        bump();
        profile.refresh_if_changed();
        assert_eq!(profile.shuangpin_counts(XIAOHE, *b"gf", *b"gr").accepted, 2);
        assert_eq!(
            profile.shuangpin_counts(XIAOHE, *b"ab", *b"ac"),
            ShuangpinTypoCounts::default()
        );
        assert!(profile.shuangpin_suppressed(XIAOHE, "gfxi"));
        let generation = profile.generation();
        profile.refresh_if_changed();
        assert_eq!(profile.generation(), generation);
    }

    /// 读的时候只认内置方案、合法的两键码和一处改动;自定义方案和写坏的行被跳过,不影响别的行。
    #[test]
    fn loading_skips_shuangpin_rows_it_cannot_use() {
        let dir = Dir::new();
        let journal = dir.journal();
        record_shuangpin_suppression(&journal, XIAOHE, "mwgfxi").unwrap();
        Connection::open(&journal)
            .unwrap()
            .execute_batch(
                "INSERT INTO shuangpin_typo_counts(profile,typed,intended,accepted,rejected) VALUES
                 ('xiaohe','gf','gr',2,1),('custom','gf','gr',5,0),('nowhere','gf','gr',5,0),
                 ('xiaohe','gF','gr',5,0),('xiaohe','gf','hr',5,0),('xiaohe','gff','gr',5,0);
                 INSERT INTO shuangpin_autocorrect_suppressions(profile,input,commits) VALUES
                 ('custom','abcd',1),('xiaohe','ab''cd',1);",
            )
            .unwrap();
        let load = load_pinyin_typo_state(&journal).unwrap();
        assert!(load.shuangpin_loaded);
        let state = load.state;
        assert_eq!(
            state.shuangpin,
            HashMap::from([(
                ShuangpinTypoKey {
                    profile: XIAOHE,
                    typed: *b"gf",
                    intended: *b"gr"
                },
                ShuangpinTypoCounts {
                    accepted: 2,
                    rejected: 1
                }
            )])
        );
        assert_eq!(
            state.shuangpin_suppressed,
            HashMap::from([(XIAOHE, HashSet::from(["mwgfxi".to_owned()]))])
        );
        assert!(state.accepted.is_empty() && state.suppressed.is_empty());
    }

    /// 档案看得见自己的写入和别的写入方:计数、抑制按方案分开,代次随之前进;查询不分配。
    #[test]
    fn the_profile_reads_and_writes_shuangpin_learning() {
        let dir = Dir::new();
        let journal = dir.journal();
        let profile = PersonalTypoProfile::shared(&journal);
        assert!(!profile.has_shuangpin_counts());
        let before = profile.generation();
        assert!(profile
            .record_shuangpin(XIAOHE, &[(*b"gf", *b"zz")], ShuangpinTypoOutcome::Accepted)
            .is_err());
        assert_eq!(profile.generation(), before);
        profile
            .record_shuangpin(XIAOHE, &[(*b"gf", *b"gr")], ShuangpinTypoOutcome::Accepted)
            .unwrap();
        profile
            .record_shuangpin(XIAOHE, &[(*b"gf", *b"gr")], ShuangpinTypoOutcome::Rejected)
            .unwrap();
        assert!(profile.generation() > before);
        assert!(profile.has_shuangpin_counts());
        assert_eq!(
            profile.shuangpin_counts(XIAOHE, *b"gf", *b"gr"),
            ShuangpinTypoCounts {
                accepted: 1,
                rejected: 1
            }
        );
        assert_eq!(
            profile.shuangpin_counts(ShuangpinProfileKind::Ziranma, *b"gf", *b"gr"),
            ShuangpinTypoCounts::default()
        );
        // 全拼那一侧的记录不受影响。
        assert_eq!(profile.accepted("gf", "gr"), 0);

        profile
            .record_shuangpin_suppression(XIAOHE, "mwgfxi")
            .unwrap();
        assert!(profile.shuangpin_suppressed(XIAOHE, "mwgfxi"));
        assert!(!profile.shuangpin_suppressed(ShuangpinProfileKind::Ziranma, "mwgfxi"));
        assert!(!profile.shuangpin_suppressed(XIAOHE, "mwgf"));
        assert!(!profile.suppressed("mwgfxi"));

        let generation = profile.generation();
        record_shuangpin_typos(
            &journal,
            XIAOHE,
            &[(*b"hc", *b"hv")],
            ShuangpinTypoOutcome::Accepted,
        )
        .unwrap();
        std::fs::File::options()
            .write(true)
            .open(&journal)
            .unwrap()
            .set_modified(SystemTime::now() + std::time::Duration::from_secs(4))
            .unwrap();
        profile.refresh_if_changed();
        assert_eq!(profile.shuangpin_counts(XIAOHE, *b"hc", *b"hv").accepted, 1);
        assert!(profile.generation() > generation);

        let (values, allocations) = crate::ime::personal_rerank::allocations::count(|| {
            (
                profile.shuangpin_counts(XIAOHE, *b"gf", *b"gr").accepted,
                profile.shuangpin_counts(XIAOHE, *b"xx", *b"xc").accepted,
                profile.shuangpin_suppressed(XIAOHE, "mwgfxi"),
            )
        });
        assert_eq!(values, (1, 0, true));
        assert_eq!(allocations, 0);
    }
}