wacore 0.7.0

Core WhatsApp protocol implementation without runtime dependencies
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
//! In-memory implementation of the [`Backend`] trait.
//!
//! Intended for testing and as a reference implementation for FFI bridges.
//! All data lives in RAM behind a single [`async_lock::Mutex`] and is lost
//! when the struct is dropped.

use hashbrown::hash_map::Entry;
use hashbrown::{Equivalent, HashMap as HbHashMap};
use std::collections::HashMap;
use std::collections::hash_map::RandomState;
use std::hash::Hash;
use std::sync::Arc;
#[cfg(any(test, feature = "test-util"))]
use std::sync::atomic::{AtomicBool, AtomicU32};
use std::sync::atomic::{AtomicI32, Ordering};

use crate::appstate::hash::HashState;
use crate::store::Device;
use crate::store::error::Result;
use crate::store::traits::*;
use async_lock::Mutex;
use async_trait::async_trait;
use bytes::Bytes;
use wacore_appstate::processor::AppStateMutationMAC;

/// Key for the sent-message store: `(chat_jid, message_id)`.
type SentMessageKey = (String, String);

/// Value stored alongside a sent message (includes timestamp for expiration).
struct SentMessageEntry {
    payload: Vec<u8>,
    timestamp: i64,
}

/// Key for pre-keys: `id`.
struct PreKeyEntry {
    record: Bytes,
}

/// Key for base-key collision detection: `(address, message_id)`.
type BaseKeyKey = (String, String);

/// Stored msg-secret value: `(secret_bytes, expires_at_secs, message_ts_secs)`.
type MsgSecretRow = (MessageSecret, i64, i64);

#[derive(Eq, Hash, PartialEq)]
struct MsgSecretKey {
    chat: Arc<str>,
    sender: Arc<str>,
    msg_id: Arc<str>,
}

#[derive(Hash)]
struct MsgSecretKeyRef<'a> {
    chat: &'a str,
    sender: &'a str,
    msg_id: &'a str,
}

impl Equivalent<MsgSecretKey> for MsgSecretKeyRef<'_> {
    fn equivalent(&self, key: &MsgSecretKey) -> bool {
        self.chat == key.chat.as_ref()
            && self.sender == key.sender.as_ref()
            && self.msg_id == key.msg_id.as_ref()
    }
}

type MsgSecretMap = HbHashMap<MsgSecretKey, MsgSecretRow, RandomState>;

/// Inner state protected by the mutex.
#[derive(Default)]
struct InMemoryState {
    // --- Signal ---
    identities: HashMap<String, [u8; 32]>,
    sessions: HashMap<String, Bytes>,
    prekeys: HashMap<u32, PreKeyEntry>,
    signed_prekeys: HashMap<u32, Vec<u8>>,
    sender_keys: HashMap<String, Vec<u8>>,

    // --- AppSync ---
    sync_keys: HashMap<Vec<u8>, AppStateSyncKey>,
    latest_sync_key_id: Option<Vec<u8>>,
    versions: HashMap<String, HashState>,
    /// `(collection_name, hex(index_mac))` -> `value_mac`
    mutation_macs: HashMap<(String, Vec<u8>), Vec<u8>>,

    // --- Protocol ---
    /// Unified per-device sender key tracking: group_jid -> (device_jid -> has_key)
    sender_key_devices: HashMap<String, HashMap<String, bool>>,
    lid_mappings: HashMap<String, LidPnMappingEntry>,
    /// Reverse index: phone_number -> lid
    pn_to_lid: HashMap<String, String>,
    base_keys: HashMap<BaseKeyKey, Vec<u8>>,
    device_lists: HashMap<String, DeviceListRecord>,
    group_metadata: HashMap<String, Vec<u8>>,
    tc_tokens: HashMap<String, TcTokenEntry>,
    sent_messages: HashMap<SentMessageKey, SentMessageEntry>,
    /// Pending inbound durability buffer: (chat, sender, id) -> (message, inserted_at).
    pending_inbound: HashMap<(String, String, String), (Vec<u8>, i64)>,

    // --- MsgSecret ---
    /// `expires_at = 0` means never expire; `message_ts = 0` means the parent
    /// event time is unknown. The keepalive cleanup prunes expired rows.
    msg_secrets: MsgSecretMap,

    // --- Device ---
    device: Option<Device>,
}

/// Hard cap on retained sent messages, bounding memory regardless of the
/// configured retention window. Time-based pruning is the client's keepalive
/// sweep (`delete_expired_sent_messages`, driven by
/// `CacheConfig::sent_message_ttl_secs`, the single source of truth for the
/// time window); this cap only guards against a burst between sweeps.
const MAX_SENT_MESSAGES: usize = 4096;

/// In-memory implementation of the full [`Backend`] trait.
///
/// Thread-safe and runtime-agnostic (uses [`async_lock::Mutex`]).
/// All data is ephemeral — it lives only as long as this struct.
pub struct InMemoryBackend {
    state: Mutex<InMemoryState>,
    next_device_id: AtomicI32,
    /// Count of `put_sessions_batch` calls. Test hook (see `test-util`): lets a
    /// harness prove receive-path flush coalescing (N receives collapse to fewer
    /// batch writes). Gated so normal builds carry neither the field nor the
    /// per-call bookkeeping.
    #[cfg(any(test, feature = "test-util"))]
    session_batch_writes: AtomicU32,
    /// Count of `put_sender_keys_batch` calls. Test hook for sender-key lease
    /// boundaries; absent from normal builds.
    #[cfg(any(test, feature = "test-util"))]
    sender_key_batch_writes: AtomicU32,
    /// When set, `put_sessions_batch` fails. Test hook (see `test-util`): lets a
    /// harness prove the send path aborts (and never hits the wire) when the
    /// ratchet advance cannot be persisted.
    #[cfg(any(test, feature = "test-util"))]
    fail_session_writes: AtomicBool,
    /// When set, `put_sender_keys_batch` fails. Test hook: the sender-key
    /// counterpart of `fail_session_writes` (wire gate must survive a failed
    /// flush).
    #[cfg(any(test, feature = "test-util"))]
    fail_sender_key_writes: AtomicBool,
}

impl InMemoryBackend {
    /// Create a new, empty in-memory store.
    pub fn new() -> Self {
        Self {
            state: Mutex::new(InMemoryState::default()),
            next_device_id: AtomicI32::new(1),
            #[cfg(any(test, feature = "test-util"))]
            session_batch_writes: AtomicU32::new(0),
            #[cfg(any(test, feature = "test-util"))]
            sender_key_batch_writes: AtomicU32::new(0),
            #[cfg(any(test, feature = "test-util"))]
            fail_session_writes: AtomicBool::new(false),
            #[cfg(any(test, feature = "test-util"))]
            fail_sender_key_writes: AtomicBool::new(false),
        }
    }

    /// Number of `put_sessions_batch` attempts since construction, including
    /// injected failures.
    #[cfg(any(test, feature = "test-util"))]
    pub fn session_batch_write_count(&self) -> u32 {
        self.session_batch_writes.load(Ordering::Relaxed)
    }

    /// Number of `put_sender_keys_batch` attempts since construction, including
    /// injected failures.
    #[cfg(any(test, feature = "test-util"))]
    pub fn sender_key_batch_write_count(&self) -> u32 {
        self.sender_key_batch_writes.load(Ordering::Relaxed)
    }

    /// Make every subsequent `put_sessions_batch` fail (or stop failing).
    #[cfg(any(test, feature = "test-util"))]
    pub fn set_fail_session_writes(&self, fail: bool) {
        self.fail_session_writes.store(fail, Ordering::Relaxed);
    }

    /// Make every subsequent `put_sender_keys_batch` fail (or stop failing).
    #[cfg(any(test, feature = "test-util"))]
    pub fn set_fail_sender_key_writes(&self, fail: bool) {
        self.fail_sender_key_writes.store(fail, Ordering::Relaxed);
    }

    /// Lets recovery tests remove only the state needed to trigger a key request.
    #[cfg(any(test, feature = "test-util"))]
    pub async fn remove_sync_key_for_test(&self, key_id: &[u8]) -> bool {
        self.state.lock().await.sync_keys.remove(key_id).is_some()
    }

    /// Keeps readiness failures attributable without exposing key material.
    #[cfg(any(test, feature = "test-util"))]
    pub async fn sync_key_count_for_test(&self) -> usize {
        self.state.lock().await.sync_keys.len()
    }
}

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

// ---------------------------------------------------------------------------
// SignalStore
// ---------------------------------------------------------------------------

#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
impl SignalStore for InMemoryBackend {
    async fn put_identity(&self, address: &str, key: [u8; 32]) -> Result<()> {
        self.state
            .lock()
            .await
            .identities
            .insert(address.to_string(), key);
        Ok(())
    }

    async fn load_identity(&self, address: &str) -> Result<Option<[u8; 32]>> {
        Ok(self.state.lock().await.identities.get(address).copied())
    }

    async fn delete_identity(&self, address: &str) -> Result<()> {
        self.state.lock().await.identities.remove(address);
        Ok(())
    }

    async fn get_session(&self, address: &str) -> Result<Option<Bytes>> {
        Ok(self.state.lock().await.sessions.get(address).cloned())
    }

    async fn put_session(&self, address: &str, session: &[u8]) -> Result<()> {
        self.state
            .lock()
            .await
            .sessions
            .insert(address.to_string(), Bytes::copy_from_slice(session));
        Ok(())
    }

    async fn put_sessions_batch(&self, sessions: &[(Arc<str>, Bytes)]) -> Result<()> {
        #[cfg(any(test, feature = "test-util"))]
        {
            self.session_batch_writes.fetch_add(1, Ordering::Relaxed);
            if self.fail_session_writes.load(Ordering::Relaxed) {
                return Err(crate::store::error::StoreError::Io(std::io::Error::other(
                    "put_sessions_batch failing (test hook)",
                )));
            }
        }
        let mut state = self.state.lock().await;
        state.sessions.reserve(sessions.len());
        for (address, session) in sessions {
            if let Some(stored) = state.sessions.get_mut(address.as_ref()) {
                *stored = session.clone();
            } else {
                state.sessions.insert(address.to_string(), session.clone());
            }
        }
        Ok(())
    }

    async fn has_session(&self, address: &str) -> Result<bool> {
        Ok(self.state.lock().await.sessions.contains_key(address))
    }

    async fn has_signal_state_for_user(&self, user: &str) -> Result<bool> {
        fn matches(addr: &str, user: &str) -> bool {
            addr.strip_prefix(user)
                .is_some_and(|rest| rest.starts_with('@') || rest.starts_with(':'))
        }
        let state = self.state.lock().await;
        Ok(state.sessions.keys().any(|k| matches(k, user))
            || state.identities.keys().any(|k| matches(k, user)))
    }

    async fn delete_session(&self, address: &str) -> Result<()> {
        self.state.lock().await.sessions.remove(address);
        Ok(())
    }

    async fn store_prekey(&self, id: u32, record: &[u8], _uploaded: bool) -> Result<()> {
        self.state.lock().await.prekeys.insert(
            id,
            PreKeyEntry {
                record: Bytes::copy_from_slice(record),
            },
        );
        Ok(())
    }

    async fn mark_prekeys_uploaded(&self, _ids: &[u32]) -> Result<()> {
        // The in-memory store does not track the uploaded flag (see
        // store_prekey); the contract that matters is NOT resurrecting
        // deleted rows, which a no-op trivially satisfies.
        Ok(())
    }

    async fn store_prekeys_batch(&self, keys: &[(u32, Bytes)], _uploaded: bool) -> Result<()> {
        let mut state = self.state.lock().await;
        for (id, record) in keys {
            state.prekeys.insert(
                *id,
                PreKeyEntry {
                    record: record.clone(),
                },
            );
        }
        Ok(())
    }

    async fn load_prekey(&self, id: u32) -> Result<Option<Bytes>> {
        Ok(self
            .state
            .lock()
            .await
            .prekeys
            .get(&id)
            .map(|e| e.record.clone()))
    }

    async fn load_prekeys_batch(&self, ids: &[u32]) -> Result<Vec<(u32, Bytes)>> {
        let state = self.state.lock().await;
        let mut result = Vec::with_capacity(ids.len());
        for &id in ids {
            if let Some(entry) = state.prekeys.get(&id) {
                result.push((id, entry.record.clone()));
            }
        }
        Ok(result)
    }

    async fn remove_prekey(&self, id: u32) -> Result<()> {
        self.state.lock().await.prekeys.remove(&id);
        Ok(())
    }

    async fn get_max_prekey_id(&self) -> Result<u32> {
        Ok(self
            .state
            .lock()
            .await
            .prekeys
            .keys()
            .copied()
            .max()
            .unwrap_or(0))
    }

    async fn store_signed_prekey(&self, id: u32, record: &[u8]) -> Result<()> {
        self.state
            .lock()
            .await
            .signed_prekeys
            .insert(id, record.to_vec());
        Ok(())
    }

    async fn load_signed_prekey(&self, id: u32) -> Result<Option<Vec<u8>>> {
        Ok(self.state.lock().await.signed_prekeys.get(&id).cloned())
    }

    async fn load_all_signed_prekeys(&self) -> Result<Vec<(u32, Vec<u8>)>> {
        Ok(self
            .state
            .lock()
            .await
            .signed_prekeys
            .iter()
            .map(|(id, rec)| (*id, rec.clone()))
            .collect())
    }

    async fn remove_signed_prekey(&self, id: u32) -> Result<()> {
        self.state.lock().await.signed_prekeys.remove(&id);
        Ok(())
    }

    async fn put_sender_key(&self, address: &str, record: &[u8]) -> Result<()> {
        #[cfg(any(test, feature = "test-util"))]
        if self.fail_sender_key_writes.load(Ordering::Relaxed) {
            return Err(crate::store::error::StoreError::Io(std::io::Error::other(
                "put_sender_key failing (test hook)",
            )));
        }
        self.state
            .lock()
            .await
            .sender_keys
            .insert(address.to_string(), record.to_vec());
        Ok(())
    }

    async fn put_sender_keys_batch(&self, sender_keys: &[(Arc<str>, Bytes)]) -> Result<()> {
        #[cfg(any(test, feature = "test-util"))]
        {
            self.sender_key_batch_writes.fetch_add(1, Ordering::Relaxed);
            if self.fail_sender_key_writes.load(Ordering::Relaxed) {
                return Err(crate::store::error::StoreError::Io(std::io::Error::other(
                    "put_sender_keys_batch failing (test hook)",
                )));
            }
        }
        let mut state = self.state.lock().await;
        state.sender_keys.reserve(sender_keys.len());
        for (address, record) in sender_keys {
            if let Some(stored) = state.sender_keys.get_mut(address.as_ref()) {
                stored.clear();
                stored.extend_from_slice(record);
            } else {
                state
                    .sender_keys
                    .insert(address.to_string(), record.to_vec());
            }
        }
        Ok(())
    }

    async fn get_sender_key(&self, address: &str) -> Result<Option<Vec<u8>>> {
        Ok(self.state.lock().await.sender_keys.get(address).cloned())
    }

    async fn delete_sender_key(&self, address: &str) -> Result<()> {
        self.state.lock().await.sender_keys.remove(address);
        Ok(())
    }
}

// ---------------------------------------------------------------------------
// AppSyncStore
// ---------------------------------------------------------------------------

#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
impl AppSyncStore for InMemoryBackend {
    async fn get_sync_key(&self, key_id: &[u8]) -> Result<Option<AppStateSyncKey>> {
        Ok(self.state.lock().await.sync_keys.get(key_id).cloned())
    }

    async fn set_sync_key(&self, key_id: &[u8], key: AppStateSyncKey) -> Result<()> {
        let mut s = self.state.lock().await;
        s.sync_keys.insert(key_id.to_vec(), key);
        s.latest_sync_key_id = Some(key_id.to_vec());
        Ok(())
    }

    async fn get_version(&self, name: &str) -> Result<HashState> {
        Ok(self
            .state
            .lock()
            .await
            .versions
            .get(name)
            .cloned()
            .unwrap_or_default())
    }

    async fn set_version(&self, name: &str, state: HashState) -> Result<()> {
        self.state
            .lock()
            .await
            .versions
            .insert(name.to_string(), state);
        Ok(())
    }

    async fn put_mutation_macs(
        &self,
        name: &str,
        _version: u64,
        mutations: &[AppStateMutationMAC],
    ) -> Result<()> {
        let mut s = self.state.lock().await;
        for m in mutations {
            s.mutation_macs
                .insert((name.to_string(), m.index_mac.clone()), m.value_mac.clone());
        }
        Ok(())
    }

    async fn get_mutation_mac(&self, name: &str, index_mac: &[u8]) -> Result<Option<Vec<u8>>> {
        Ok(self
            .state
            .lock()
            .await
            .mutation_macs
            .get(&(name.to_string(), index_mac.to_vec()))
            .cloned())
    }

    async fn delete_mutation_macs(&self, name: &str, index_macs: &[Vec<u8>]) -> Result<()> {
        let mut s = self.state.lock().await;
        for im in index_macs {
            s.mutation_macs.remove(&(name.to_string(), im.clone()));
        }
        Ok(())
    }

    async fn clear_mutation_macs(&self, name: &str) -> Result<()> {
        self.state
            .lock()
            .await
            .mutation_macs
            .retain(|(n, _), _| n != name);
        Ok(())
    }

    async fn get_latest_sync_key_id(&self) -> Result<Option<Vec<u8>>> {
        Ok(self.state.lock().await.latest_sync_key_id.clone())
    }
}

// ---------------------------------------------------------------------------
// ProtocolStore
// ---------------------------------------------------------------------------

#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
impl ProtocolStore for InMemoryBackend {
    // --- Per-Device Sender Key Tracking ---

    async fn get_sender_key_devices(&self, group_jid: &str) -> Result<Vec<(String, bool)>> {
        Ok(self
            .state
            .lock()
            .await
            .sender_key_devices
            .get(group_jid)
            .map(|map| map.iter().map(|(k, v)| (k.clone(), *v)).collect())
            .unwrap_or_default())
    }

    async fn set_sender_key_status(&self, group_jid: &str, entries: &[(&str, bool)]) -> Result<()> {
        let mut s = self.state.lock().await;
        let map = s
            .sender_key_devices
            .entry(group_jid.to_string())
            .or_default();
        for (device_jid, has_key) in entries {
            map.insert(device_jid.to_string(), *has_key);
        }
        Ok(())
    }

    async fn clear_sender_key_devices(&self, group_jid: &str) -> Result<()> {
        self.state.lock().await.sender_key_devices.remove(group_jid);
        Ok(())
    }

    async fn clear_all_sender_key_devices(&self) -> Result<()> {
        self.state.lock().await.sender_key_devices.clear();
        Ok(())
    }

    async fn delete_sender_key_device_rows(&self, device_jids: &[&str]) -> Result<()> {
        if device_jids.is_empty() {
            return Ok(());
        }
        let mut state = self.state.lock().await;
        for group_map in state.sender_key_devices.values_mut() {
            group_map.retain(|jid, _| !device_jids.contains(&jid.as_str()));
        }
        Ok(())
    }

    // --- LID-PN Mapping ---

    async fn get_lid_mapping(&self, lid: &str) -> Result<Option<LidPnMappingEntry>> {
        Ok(self.state.lock().await.lid_mappings.get(lid).cloned())
    }

    async fn get_pn_mapping(&self, phone: &str) -> Result<Option<LidPnMappingEntry>> {
        let s = self.state.lock().await;
        let entry = s
            .pn_to_lid
            .get(phone)
            .and_then(|lid| s.lid_mappings.get(lid))
            .cloned();
        Ok(entry)
    }

    async fn put_lid_mapping(&self, entry: &LidPnMappingEntry) -> Result<()> {
        let mut s = self.state.lock().await;
        // Remove stale reverse entry if the LID was previously mapped to a different phone number
        if let Some(old_phone) = s
            .lid_mappings
            .get(&entry.lid)
            .filter(|old| old.phone_number != entry.phone_number)
            .map(|old| old.phone_number.clone())
        {
            s.pn_to_lid.remove(&old_phone);
        }
        s.pn_to_lid
            .insert(entry.phone_number.clone(), entry.lid.clone());
        s.lid_mappings.insert(entry.lid.clone(), entry.clone());
        Ok(())
    }

    async fn get_all_lid_mappings(&self) -> Result<Vec<LidPnMappingEntry>> {
        Ok(self
            .state
            .lock()
            .await
            .lid_mappings
            .values()
            .cloned()
            .collect())
    }

    // --- Base Key Collision Detection ---

    async fn save_base_key(&self, address: &str, message_id: &str, base_key: &[u8]) -> Result<()> {
        self.state.lock().await.base_keys.insert(
            (address.to_string(), message_id.to_string()),
            base_key.to_vec(),
        );
        Ok(())
    }

    async fn has_same_base_key(
        &self,
        address: &str,
        message_id: &str,
        current_base_key: &[u8],
    ) -> Result<bool> {
        let s = self.state.lock().await;
        let same = s
            .base_keys
            .get(&(address.to_string(), message_id.to_string()))
            .is_some_and(|stored| stored == current_base_key);
        Ok(same)
    }

    async fn delete_base_key(&self, address: &str, message_id: &str) -> Result<()> {
        self.state
            .lock()
            .await
            .base_keys
            .remove(&(address.to_string(), message_id.to_string()));
        Ok(())
    }

    // --- Device Registry ---

    async fn update_device_list(&self, record: DeviceListRecord) -> Result<()> {
        self.state
            .lock()
            .await
            .device_lists
            .insert(record.user.clone(), record);
        Ok(())
    }

    async fn get_devices(&self, user: &str) -> Result<Option<DeviceListRecord>> {
        Ok(self.state.lock().await.device_lists.get(user).cloned())
    }

    async fn delete_devices(&self, user: &str) -> Result<()> {
        self.state.lock().await.device_lists.remove(user);
        Ok(())
    }

    async fn get_group_metadata(&self, group_jid: &str) -> Result<Option<Vec<u8>>> {
        Ok(self
            .state
            .lock()
            .await
            .group_metadata
            .get(group_jid)
            .cloned())
    }

    async fn put_group_metadata(&self, group_jid: &str, blob: &[u8]) -> Result<()> {
        self.state
            .lock()
            .await
            .group_metadata
            .insert(group_jid.to_string(), blob.to_vec());
        Ok(())
    }

    async fn delete_group_metadata(&self, group_jid: &str) -> Result<()> {
        self.state.lock().await.group_metadata.remove(group_jid);
        Ok(())
    }

    // --- TcToken Storage ---

    async fn get_tc_token(&self, jid: &str) -> Result<Option<TcTokenEntry>> {
        Ok(self.state.lock().await.tc_tokens.get(jid).cloned())
    }

    async fn put_tc_token(&self, jid: &str, entry: &TcTokenEntry) -> Result<()> {
        self.state
            .lock()
            .await
            .tc_tokens
            .insert(jid.to_string(), entry.clone());
        Ok(())
    }

    async fn delete_tc_token(&self, jid: &str) -> Result<()> {
        self.state.lock().await.tc_tokens.remove(jid);
        Ok(())
    }

    async fn get_all_tc_token_jids(&self) -> Result<Vec<String>> {
        Ok(self.state.lock().await.tc_tokens.keys().cloned().collect())
    }

    async fn delete_expired_tc_tokens(&self, token_cutoff: i64, sender_cutoff: i64) -> Result<u32> {
        let mut s = self.state.lock().await;
        let before = s.tc_tokens.len();
        // Keep a row while either window is still live: the received token or the
        // sender bucket. A row is dropped only when both are stale.
        s.tc_tokens.retain(|_, entry| {
            let token_live = !entry.token.is_empty() && entry.token_timestamp >= token_cutoff;
            let sender_live = entry.sender_timestamp.is_some_and(|ts| ts >= sender_cutoff);
            token_live || sender_live
        });
        Ok((before - s.tc_tokens.len()) as u32)
    }

    async fn touch_tc_token_sender_timestamp(
        &self,
        jid: &str,
        sender_timestamp: i64,
    ) -> Result<()> {
        let mut s = self.state.lock().await;
        match s.tc_tokens.get_mut(jid) {
            Some(entry) => {
                entry.sender_timestamp = Some(
                    entry
                        .sender_timestamp
                        .map_or(sender_timestamp, |e| e.max(sender_timestamp)),
                );
            }
            None => {
                s.tc_tokens.insert(
                    jid.to_string(),
                    TcTokenEntry {
                        token: Vec::new(),
                        token_timestamp: sender_timestamp,
                        sender_timestamp: Some(sender_timestamp),
                    },
                );
            }
        }
        Ok(())
    }

    async fn store_received_tc_token(
        &self,
        jid: &str,
        token: &[u8],
        token_timestamp: i64,
    ) -> Result<()> {
        let mut s = self.state.lock().await;
        match s.tc_tokens.get_mut(jid) {
            Some(entry) => {
                // Newer-wins (see the trait doc): don't let a stale write
                // clobber a fresher token.
                if entry.token.is_empty() || token_timestamp >= entry.token_timestamp {
                    entry.token = token.to_vec();
                    entry.token_timestamp = token_timestamp;
                    // sender_timestamp left untouched
                }
            }
            None => {
                s.tc_tokens.insert(
                    jid.to_string(),
                    TcTokenEntry {
                        token: token.to_vec(),
                        token_timestamp,
                        sender_timestamp: None,
                    },
                );
            }
        }
        Ok(())
    }

    // --- Sent Message Store ---

    async fn store_sent_message(
        &self,
        chat_jid: &str,
        message_id: &str,
        payload: &[u8],
    ) -> Result<()> {
        let now = crate::time::now_secs();
        let mut s = self.state.lock().await;

        // Memory bound only: when the map hits the cap, drop the oldest entries
        // (by timestamp) down to 3/4 of it so this scan amortizes across many
        // inserts. Time-based pruning is the caller's keepalive sweep.
        //
        // Only the timestamps are collected: cloning every key to sort them
        // allocated two Strings per retained entry on each eviction (4096 keys
        // per 1024 inserts under load) while holding the state lock, which
        // showed up both as per-message churn and as a latency spike.
        // `select_nth_unstable` finds the cutoff in O(n) without ordering the
        // rest, then two passes apply it: everything strictly older goes, and
        // the cutoff's own bucket tops the removal up to the exact count. The
        // split is what keeps the policy oldest-first, since map iteration
        // order is arbitrary and a single pass could evict an entry AT the
        // cutoff while keeping one below it. The exact count matters because a
        // flood puts every entry in the same second: with one bucket for the
        // whole map, dropping all of "timestamp <= cutoff" would clear it.
        if s.sent_messages.len() >= MAX_SENT_MESSAGES {
            let target = MAX_SENT_MESSAGES * 3 / 4;
            let drop_count = s.sent_messages.len().saturating_sub(target);
            if drop_count > 0 {
                let mut ages: Vec<i64> = s.sent_messages.values().map(|e| e.timestamp).collect();
                let (_, &mut cutoff, _) = ages.select_nth_unstable(drop_count - 1);
                let mut removed = 0usize;
                s.sent_messages.retain(|_, e| {
                    if e.timestamp < cutoff {
                        removed += 1;
                        false
                    } else {
                        true
                    }
                });
                let mut remaining = drop_count.saturating_sub(removed);
                if remaining > 0 {
                    s.sent_messages.retain(|_, e| {
                        if remaining > 0 && e.timestamp == cutoff {
                            remaining -= 1;
                            false
                        } else {
                            true
                        }
                    });
                }
            }
        }

        s.sent_messages.insert(
            (chat_jid.to_string(), message_id.to_string()),
            SentMessageEntry {
                payload: payload.to_vec(),
                timestamp: now,
            },
        );
        Ok(())
    }

    async fn take_sent_message(&self, chat_jid: &str, message_id: &str) -> Result<Option<Vec<u8>>> {
        Ok(self
            .state
            .lock()
            .await
            .sent_messages
            .remove(&(chat_jid.to_string(), message_id.to_string()))
            .map(|e| e.payload))
    }

    async fn delete_expired_sent_messages(&self, cutoff_timestamp: i64) -> Result<u32> {
        let mut s = self.state.lock().await;
        let before = s.sent_messages.len();
        s.sent_messages
            .retain(|_, entry| entry.timestamp >= cutoff_timestamp);
        Ok((before - s.sent_messages.len()) as u32)
    }

    async fn store_pending_inbound(
        &self,
        chat: &str,
        sender: &str,
        id: &str,
        message: &[u8],
    ) -> Result<()> {
        let now = crate::time::now_secs();
        self.state.lock().await.pending_inbound.insert(
            (chat.to_string(), sender.to_string(), id.to_string()),
            (message.to_vec(), now),
        );
        Ok(())
    }

    async fn get_pending_inbound(
        &self,
        chat: &str,
        sender: &str,
        id: &str,
    ) -> Result<Option<Vec<u8>>> {
        let key = (chat.to_string(), sender.to_string(), id.to_string());
        Ok(self
            .state
            .lock()
            .await
            .pending_inbound
            .get(&key)
            .map(|(bytes, _)| bytes.clone()))
    }

    async fn delete_pending_inbound(&self, chat: &str, sender: &str, id: &str) -> Result<()> {
        let key = (chat.to_string(), sender.to_string(), id.to_string());
        self.state.lock().await.pending_inbound.remove(&key);
        Ok(())
    }

    async fn delete_expired_pending_inbound(&self, cutoff_timestamp: i64) -> Result<u32> {
        let mut s = self.state.lock().await;
        let before = s.pending_inbound.len();
        s.pending_inbound
            .retain(|_, (_, inserted_at)| *inserted_at >= cutoff_timestamp);
        Ok((before - s.pending_inbound.len()) as u32)
    }
}

// ---------------------------------------------------------------------------
// MsgSecretStore
// ---------------------------------------------------------------------------

#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
impl MsgSecretStore for InMemoryBackend {
    async fn put_msg_secrets(&self, entries: Vec<MsgSecretEntry>) -> Result<usize> {
        use crate::store::traits::{merge_msg_secret_expiry, merge_msg_secret_message_ts};
        let stored = entries.len();
        let mut state = self.state.lock().await;
        // Initial history batches are overwhelmingly new rows, so reserve
        // once. Once populated, a batch may be mostly overwrites; reserving its
        // full length then would grow the table without adding any rows.
        if state.msg_secrets.is_empty() {
            state.msg_secrets.reserve(stored);
        }
        for entry in entries {
            let key = MsgSecretKey {
                chat: entry.chat,
                sender: entry.sender,
                msg_id: entry.msg_id,
            };
            match state.msg_secrets.entry(key) {
                Entry::Occupied(mut occupied) => {
                    let (secret, expires_at, message_ts) = occupied.get_mut();
                    *secret = entry.secret;
                    *expires_at = merge_msg_secret_expiry(*expires_at, entry.expires_at);
                    *message_ts = merge_msg_secret_message_ts(*message_ts, entry.message_ts);
                }
                Entry::Vacant(vacant) => {
                    vacant.insert((entry.secret, entry.expires_at, entry.message_ts));
                }
            }
        }
        Ok(stored)
    }

    async fn get_msg_secret(
        &self,
        chat: &str,
        sender: &str,
        msg_id: &str,
    ) -> Result<Option<Vec<u8>>> {
        Ok(self
            .get_msg_secret_with_ts(chat, sender, msg_id)
            .await?
            .map(|(secret, _)| secret))
    }

    async fn get_msg_secret_with_ts(
        &self,
        chat: &str,
        sender: &str,
        msg_id: &str,
    ) -> Result<Option<(Vec<u8>, i64)>> {
        Ok(self
            .state
            .lock()
            .await
            .msg_secrets
            .get(&MsgSecretKeyRef {
                chat,
                sender,
                msg_id,
            })
            .map(|(secret, _, message_ts)| (secret.to_vec(), *message_ts)))
    }

    async fn delete_expired_msg_secrets(&self, cutoff_timestamp: i64) -> Result<u32> {
        let mut state = self.state.lock().await;
        let before = state.msg_secrets.len();
        // Keep rows with no deadline (0 = never) or a deadline still in the future.
        state
            .msg_secrets
            .retain(|_, (_, expires_at, _)| *expires_at == 0 || *expires_at > cutoff_timestamp);
        Ok((before - state.msg_secrets.len()) as u32)
    }
}

// ---------------------------------------------------------------------------
// DeviceStore
// ---------------------------------------------------------------------------

#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
impl DeviceStore for InMemoryBackend {
    async fn save(&self, device: &Device) -> Result<()> {
        self.state.lock().await.device = Some(device.clone());
        Ok(())
    }

    async fn load(&self) -> Result<Option<Device>> {
        Ok(self.state.lock().await.device.clone())
    }

    async fn exists(&self) -> Result<bool> {
        Ok(self.state.lock().await.device.is_some())
    }

    async fn create(&self) -> Result<i32> {
        let id = self.next_device_id.fetch_add(1, Ordering::Relaxed);
        // Materialize a default Device so that `exists()` returns true after `create()`.
        let mut state = self.state.lock().await;
        if state.device.is_none() {
            state.device = Some(Device::new());
        }
        Ok(id)
    }
}

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

    fn is_backend<T: Backend>() {}

    #[test]
    fn in_memory_backend_implements_backend() {
        is_backend::<InMemoryBackend>();
    }

    #[tokio::test]
    async fn put_sessions_batch_inserts_and_updates() {
        let backend = InMemoryBackend::new();
        let first: Arc<str> = "15550000001:1@s.whatsapp.net".into();
        let second: Arc<str> = "15550000002:2@s.whatsapp.net".into();

        backend
            .put_sessions_batch(&[
                (first.clone(), Bytes::from_static(b"first")),
                (second.clone(), Bytes::from_static(b"second")),
            ])
            .await
            .unwrap();
        backend
            .put_sessions_batch(&[(first.clone(), Bytes::from_static(b"updated"))])
            .await
            .unwrap();

        assert_eq!(
            backend.get_session(&first).await.unwrap().unwrap(),
            Bytes::from_static(b"updated")
        );
        assert_eq!(
            backend.get_session(&second).await.unwrap().unwrap(),
            Bytes::from_static(b"second")
        );
    }

    #[tokio::test]
    async fn group_metadata_round_trip() {
        use crate::store::traits::ProtocolStore;
        let backend = InMemoryBackend::new();
        let jid = "120363000000000001@g.us";

        assert!(backend.get_group_metadata(jid).await.unwrap().is_none());
        backend.put_group_metadata(jid, b"blob-v1").await.unwrap();
        assert_eq!(
            backend.get_group_metadata(jid).await.unwrap().as_deref(),
            Some(&b"blob-v1"[..])
        );
        backend.put_group_metadata(jid, b"blob-v2").await.unwrap();
        assert_eq!(
            backend.get_group_metadata(jid).await.unwrap().as_deref(),
            Some(&b"blob-v2"[..])
        );
        // Delete drops the blob so the next query re-fetches in full.
        backend.delete_group_metadata(jid).await.unwrap();
        assert!(backend.get_group_metadata(jid).await.unwrap().is_none());
    }

    #[tokio::test]
    async fn clear_mutation_macs_wipes_only_named_collection() {
        use crate::store::traits::AppSyncStore;
        let backend = InMemoryBackend::new();
        let mac = |i: u8, v: u8| AppStateMutationMAC {
            index_mac: vec![i],
            value_mac: vec![v],
        };
        backend
            .put_mutation_macs("regular", 1, &[mac(1, 10)])
            .await
            .unwrap();
        backend
            .put_mutation_macs("critical", 1, &[mac(2, 20)])
            .await
            .unwrap();

        backend.clear_mutation_macs("regular").await.unwrap();

        assert!(
            backend
                .get_mutation_mac("regular", &[1])
                .await
                .unwrap()
                .is_none()
        );
        assert_eq!(
            backend.get_mutation_mac("critical", &[2]).await.unwrap(),
            Some(vec![20])
        );
    }

    #[tokio::test]
    async fn has_signal_state_for_user_matches_by_user_prefix() {
        let backend = InMemoryBackend::new();
        let user = "5511999990000";

        assert!(!backend.has_signal_state_for_user(user).await.unwrap());

        // Device 0 is keyed `user@server`.
        backend
            .put_session("5511999990000@s.whatsapp.net", b"sess")
            .await
            .unwrap();
        assert!(backend.has_signal_state_for_user(user).await.unwrap());

        // A different user that this one is a prefix of must NOT match.
        let other = InMemoryBackend::new();
        other
            .put_session("55119999900001@s.whatsapp.net", b"sess")
            .await
            .unwrap();
        assert!(!other.has_signal_state_for_user(user).await.unwrap());

        // Non-zero device is keyed `user:dev@server`; identity-only also counts.
        let dev = InMemoryBackend::new();
        dev.put_identity("5511999990000:5@s.whatsapp.net", [7u8; 32])
            .await
            .unwrap();
        assert!(dev.has_signal_state_for_user(user).await.unwrap());
    }

    #[tokio::test]
    async fn store_sent_message_is_memory_bounded() {
        let backend = InMemoryBackend::new();
        for i in 0..(MAX_SENT_MESSAGES + 500) {
            backend
                .store_sent_message("chat@g.us", &format!("m{i}"), b"payload")
                .await
                .unwrap();
        }
        let len = backend.state.lock().await.sent_messages.len();
        assert!(
            len <= MAX_SENT_MESSAGES,
            "sent_messages must stay within the hard cap, got {len}"
        );
        // The most recently stored message is inserted after eviction, so it
        // always survives.
        let last = format!("m{}", MAX_SENT_MESSAGES + 500 - 1);
        assert!(
            backend
                .take_sent_message("chat@g.us", &last)
                .await
                .unwrap()
                .is_some(),
            "the newest message must survive count-cap eviction"
        );
    }

    /// Under a flood every entry lands in the same second, so the eviction
    /// cutoff is a timestamp shared by the whole map. Dropping everything at or
    /// below it would clear the store instead of trimming it, losing the
    /// retry/receipt payloads of messages that were just sent.
    #[tokio::test]
    async fn store_sent_message_eviction_trims_when_all_timestamps_tie() {
        let backend = InMemoryBackend::new();
        for i in 0..MAX_SENT_MESSAGES {
            backend
                .store_sent_message("chat@g.us", &format!("m{i}"), b"payload")
                .await
                .unwrap();
        }
        // Pin the tie instead of relying on the loop finishing inside one
        // second: the clock advancing mid-run would silently exercise the
        // ordinary multi-bucket path rather than the case under test.
        {
            let mut s = backend.state.lock().await;
            for entry in s.sent_messages.values_mut() {
                entry.timestamp = 1_000;
            }
        }

        // The map is at the cap, so this insert is the one that evicts.
        backend
            .store_sent_message("chat@g.us", "trigger", b"payload")
            .await
            .unwrap();

        let target = MAX_SENT_MESSAGES * 3 / 4;
        let s = backend.state.lock().await;
        assert_eq!(
            s.sent_messages.len(),
            target + 1,
            "eviction must trim to 3/4 of the cap plus the insert that triggered it"
        );
        assert!(
            s.sent_messages
                .contains_key(&("chat@g.us".to_string(), "trigger".to_string())),
            "the insert that triggered eviction must survive it"
        );
    }

    /// With distinct timestamps the cutoff bucket must not shield older
    /// entries: arbitrary map iteration order used to decide who went first.
    #[tokio::test]
    async fn store_sent_message_eviction_drops_the_oldest_first() {
        let backend = InMemoryBackend::new();
        for i in 0..MAX_SENT_MESSAGES {
            backend
                .store_sent_message("chat@g.us", &format!("m{i}"), b"payload")
                .await
                .unwrap();
        }
        // Two buckets: a minority strictly older than the rest. Every one of the
        // old bucket has to go before anything from the newer bucket does.
        let old_ids: Vec<String> = (0..16).map(|i| format!("m{i}")).collect();
        {
            let mut s = backend.state.lock().await;
            for (key, entry) in s.sent_messages.iter_mut() {
                entry.timestamp = if old_ids.contains(&key.1) { 500 } else { 1_000 };
            }
        }

        backend
            .store_sent_message("chat@g.us", "trigger", b"payload")
            .await
            .unwrap();

        let s = backend.state.lock().await;
        for id in &old_ids {
            assert!(
                !s.sent_messages
                    .contains_key(&("chat@g.us".to_string(), id.clone())),
                "entry {id} is older than the cutoff and must have been evicted"
            );
        }
    }

    #[tokio::test]
    async fn msg_secret_round_trip() {
        let backend = InMemoryBackend::new();
        let secret = [7u8; 32];
        backend
            .put_msg_secret("12345@s.whatsapp.net", "9999@lid", "MID1", &secret)
            .await
            .unwrap();
        let got = backend
            .get_msg_secret("12345@s.whatsapp.net", "9999@lid", "MID1")
            .await
            .unwrap();
        assert_eq!(got.as_deref(), Some(&secret[..]));
    }

    #[tokio::test]
    async fn msg_secret_miss_returns_none() {
        let backend = InMemoryBackend::new();
        assert!(
            backend
                .get_msg_secret("12345@s.whatsapp.net", "9999@lid", "MID1")
                .await
                .unwrap()
                .is_none(),
            "absent secret must return None"
        );
    }

    #[tokio::test]
    async fn msg_secret_keyed_by_all_three_columns() {
        // Same chat+sender, different msg_id → independent entries.
        // Same chat+msg_id, different sender → independent entries.
        // Same sender+msg_id, different chat → independent entries.
        let backend = InMemoryBackend::new();
        backend
            .put_msg_secret("chatA", "senderX", "M1", &[1u8; 32])
            .await
            .unwrap();
        backend
            .put_msg_secret("chatA", "senderX", "M2", &[2u8; 32])
            .await
            .unwrap();
        backend
            .put_msg_secret("chatA", "senderY", "M1", &[3u8; 32])
            .await
            .unwrap();
        backend
            .put_msg_secret("chatB", "senderX", "M1", &[4u8; 32])
            .await
            .unwrap();

        assert_eq!(
            backend
                .get_msg_secret("chatA", "senderX", "M1")
                .await
                .unwrap()
                .unwrap(),
            vec![1u8; 32]
        );
        assert_eq!(
            backend
                .get_msg_secret("chatA", "senderX", "M2")
                .await
                .unwrap()
                .unwrap(),
            vec![2u8; 32]
        );
        assert_eq!(
            backend
                .get_msg_secret("chatA", "senderY", "M1")
                .await
                .unwrap()
                .unwrap(),
            vec![3u8; 32]
        );
        assert_eq!(
            backend
                .get_msg_secret("chatB", "senderX", "M1")
                .await
                .unwrap()
                .unwrap(),
            vec![4u8; 32]
        );
    }

    #[tokio::test]
    async fn msg_secret_batch_round_trip_and_overwrite() {
        let backend = InMemoryBackend::new();
        let stored = backend
            .put_msg_secrets(vec![
                MsgSecretEntry {
                    chat: "chat".into(),
                    sender: "sender".into(),
                    msg_id: "M1".into(),
                    secret: [1u8; crate::reporting_token::MESSAGE_SECRET_SIZE],
                    expires_at: 0,
                    message_ts: 0,
                },
                MsgSecretEntry {
                    chat: "chat".into(),
                    sender: "sender".into(),
                    msg_id: "M2".into(),
                    secret: [2u8; crate::reporting_token::MESSAGE_SECRET_SIZE],
                    expires_at: 0,
                    message_ts: 0,
                },
                MsgSecretEntry {
                    chat: "chat".into(),
                    sender: "sender".into(),
                    msg_id: "M1".into(),
                    secret: [9u8; crate::reporting_token::MESSAGE_SECRET_SIZE],
                    expires_at: 0,
                    message_ts: 0,
                },
            ])
            .await
            .unwrap();

        assert_eq!(stored, 3);
        assert_eq!(
            backend
                .get_msg_secret("chat", "sender", "M1")
                .await
                .unwrap()
                .unwrap(),
            vec![9u8; 32]
        );
        assert_eq!(
            backend
                .get_msg_secret("chat", "sender", "M2")
                .await
                .unwrap()
                .unwrap(),
            vec![2u8; 32]
        );
    }

    #[tokio::test]
    async fn delete_expired_msg_secrets_removes_only_old_rows() {
        let backend = InMemoryBackend::new();
        backend
            .put_msg_secret("c", "s", "OLD", &[1u8; 32])
            .await
            .unwrap();
        // Set a deadline already in the past to simulate an expired row.
        {
            let mut state = backend.state.lock().await;
            let entry = state
                .msg_secrets
                .get_mut(&MsgSecretKeyRef {
                    chat: "c",
                    sender: "s",
                    msg_id: "OLD",
                })
                .unwrap();
            entry.1 = crate::time::now_secs() - 86_400 * 30;
        }
        // NEW keeps the default `expires_at = 0` (never), so it survives.
        backend
            .put_msg_secret("c", "s", "NEW", &[2u8; 32])
            .await
            .unwrap();

        let cutoff = crate::time::now_secs() - 86_400 * 14;
        let removed = backend.delete_expired_msg_secrets(cutoff).await.unwrap();
        assert_eq!(removed, 1);
        assert!(
            backend
                .get_msg_secret("c", "s", "OLD")
                .await
                .unwrap()
                .is_none()
        );
        assert!(
            backend
                .get_msg_secret("c", "s", "NEW")
                .await
                .unwrap()
                .is_some()
        );
    }

    #[tokio::test]
    async fn msg_secret_overwrite_on_same_key() {
        let backend = InMemoryBackend::new();
        backend
            .put_msg_secret("chat", "sender", "M", &[1u8; 32])
            .await
            .unwrap();
        backend
            .put_msg_secret("chat", "sender", "M", &[9u8; 32])
            .await
            .unwrap();
        assert_eq!(
            backend
                .get_msg_secret("chat", "sender", "M")
                .await
                .unwrap()
                .unwrap(),
            vec![9u8; 32],
            "last write wins for the same composite key"
        );
    }

    #[tokio::test]
    async fn touch_tc_token_creates_placeholder_then_preserves_real_token() {
        let backend = InMemoryBackend::new();

        backend
            .touch_tc_token_sender_timestamp("u1", 1000)
            .await
            .unwrap();
        let placeholder = backend.get_tc_token("u1").await.unwrap().unwrap();
        assert!(placeholder.token.is_empty());
        assert_eq!(placeholder.sender_timestamp, Some(1000));

        // A real token stored by the notification path must survive a later touch.
        backend
            .put_tc_token(
                "u1",
                &TcTokenEntry {
                    token: vec![7, 8, 9],
                    token_timestamp: 2000,
                    sender_timestamp: None,
                },
            )
            .await
            .unwrap();
        backend
            .touch_tc_token_sender_timestamp("u1", 3000)
            .await
            .unwrap();

        let merged = backend.get_tc_token("u1").await.unwrap().unwrap();
        assert_eq!(
            merged.token,
            vec![7, 8, 9],
            "touch must not clobber the real token"
        );
        assert_eq!(merged.token_timestamp, 2000);
        assert_eq!(merged.sender_timestamp, Some(3000));
    }

    #[tokio::test]
    async fn touch_sender_timestamp_only_advances() {
        let backend = InMemoryBackend::new();
        backend
            .touch_tc_token_sender_timestamp("uadv", 5000)
            .await
            .unwrap();
        // An older touch (e.g. a stale history-sync sender epoch) must not regress.
        backend
            .touch_tc_token_sender_timestamp("uadv", 3000)
            .await
            .unwrap();
        assert_eq!(
            backend
                .get_tc_token("uadv")
                .await
                .unwrap()
                .unwrap()
                .sender_timestamp,
            Some(5000)
        );
    }

    #[tokio::test]
    async fn store_received_tc_token_preserves_sender_timestamp() {
        let backend = InMemoryBackend::new();
        // Placeholder from the issuance path.
        backend
            .touch_tc_token_sender_timestamp("u2", 5000)
            .await
            .unwrap();

        // Notification stores the real token; the sender bucket must survive.
        backend
            .store_received_tc_token("u2", &[1, 2, 3], 4000)
            .await
            .unwrap();

        let entry = backend.get_tc_token("u2").await.unwrap().unwrap();
        assert_eq!(entry.token, vec![1, 2, 3]);
        assert_eq!(entry.token_timestamp, 4000);
        assert_eq!(
            entry.sender_timestamp,
            Some(5000),
            "store_received_tc_token must not drop the sender bucket"
        );

        // No prior entry: sender_timestamp starts unset.
        backend
            .store_received_tc_token("u3", &[9], 4000)
            .await
            .unwrap();
        let fresh = backend.get_tc_token("u3").await.unwrap().unwrap();
        assert_eq!(fresh.sender_timestamp, None);
    }

    #[tokio::test]
    async fn store_received_tc_token_is_newer_wins() {
        let backend = InMemoryBackend::new();

        // First real token at t=5000.
        backend
            .store_received_tc_token("c", &[1, 1, 1], 5000)
            .await
            .unwrap();

        // A stale write (older timestamp) must not clobber the fresher token —
        // this is what lets concurrent history-sync chunks converge lock-free.
        backend
            .store_received_tc_token("c", &[2, 2, 2], 3000)
            .await
            .unwrap();
        let e = backend.get_tc_token("c").await.unwrap().unwrap();
        assert_eq!(e.token, vec![1, 1, 1], "older write must not overwrite");
        assert_eq!(e.token_timestamp, 5000);

        // A newer write wins.
        backend
            .store_received_tc_token("c", &[3, 3, 3], 7000)
            .await
            .unwrap();
        let e = backend.get_tc_token("c").await.unwrap().unwrap();
        assert_eq!(e.token, vec![3, 3, 3]);
        assert_eq!(e.token_timestamp, 7000);

        // A byte-less placeholder (sender epoch t=9000) never blocks a real token,
        // even when the real token's timestamp is older than the placeholder's.
        backend
            .touch_tc_token_sender_timestamp("p", 9000)
            .await
            .unwrap();
        backend
            .store_received_tc_token("p", &[4, 4, 4], 6000)
            .await
            .unwrap();
        let e = backend.get_tc_token("p").await.unwrap().unwrap();
        assert_eq!(
            e.token,
            vec![4, 4, 4],
            "placeholder must accept first real token"
        );
        assert_eq!(e.token_timestamp, 6000);
        assert_eq!(e.sender_timestamp, Some(9000), "sender bucket preserved");
    }

    #[tokio::test]
    async fn prune_respects_sender_and_token_windows() {
        let backend = InMemoryBackend::new();
        // token_cutoff = 1000, sender_cutoff = 2000 (wider sender window).

        // Recent placeholder: sender bucket still live → kept.
        backend
            .touch_tc_token_sender_timestamp("recent_ph", 2500)
            .await
            .unwrap();
        // Stale placeholder: both windows passed → pruned.
        backend
            .touch_tc_token_sender_timestamp("stale_ph", 100)
            .await
            .unwrap();
        // Expired token but recent sender bucket → kept (issuance state survives).
        backend
            .put_tc_token(
                "expired_tok_live_sender",
                &TcTokenEntry {
                    token: vec![1],
                    token_timestamp: 1,
                    sender_timestamp: Some(2500),
                },
            )
            .await
            .unwrap();
        // Expired token, no sender state → pruned.
        backend
            .put_tc_token(
                "orphan_expired",
                &TcTokenEntry {
                    token: vec![2],
                    token_timestamp: 1,
                    sender_timestamp: None,
                },
            )
            .await
            .unwrap();
        // Fresh received token → kept.
        backend
            .put_tc_token(
                "fresh_tok",
                &TcTokenEntry {
                    token: vec![3],
                    token_timestamp: 5000,
                    sender_timestamp: None,
                },
            )
            .await
            .unwrap();

        let removed = backend.delete_expired_tc_tokens(1000, 2000).await.unwrap();
        assert_eq!(removed, 2, "only fully-stale rows are pruned");
        assert!(backend.get_tc_token("recent_ph").await.unwrap().is_some());
        assert!(backend.get_tc_token("stale_ph").await.unwrap().is_none());
        assert!(
            backend
                .get_tc_token("expired_tok_live_sender")
                .await
                .unwrap()
                .is_some()
        );
        assert!(
            backend
                .get_tc_token("orphan_expired")
                .await
                .unwrap()
                .is_none()
        );
        assert!(backend.get_tc_token("fresh_tok").await.unwrap().is_some());
    }
}