crossbank 0.1.2

Local, on-device key/value storage for Rust — one API on native (redb) and in the browser (IndexedDB). A Hive-shaped replacement, with no network, server, or sync.
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
//! The eager locker: everything resident, reads synchronous.
//!
//! Hive's `Box`, and the reason Hive feels the way it does — `get()` returns
//! immediately because the value is already here. Ideal for settings, theme
//! state, feature flags: small, hot, and read from render paths that cannot
//! await.
//!
//! Values are held as `Arc<T>`, decoded once at open. That keeps `get()` O(1),
//! avoids requiring `T: Clone`, and means a decode failure surfaces at open —
//! where it can be reported — rather than from an infallible getter.
//!
//! # Why this type refuses things
//!
//! A synchronous, infallible `get()` cannot await a chunk fetch, cannot await a
//! refetch after another tab invalidates a key, and cannot report an error. So
//! the type refuses, up front, anything that would put it in that position:
//! oversized values, oversized contents at open, and eviction policies.
//! Refusing loudly beats a getter that lies.

use std::collections::BTreeMap;
use std::ops::Bound;
use std::sync::atomic::AtomicBool;
use std::sync::{Arc, Mutex};

use serde::{de::DeserializeOwned, Serialize};

use crate::backend::api::Backend;
use crate::codec::FilterChain;
use crate::error::{Error, Result};
use crate::key::LockerId;

use super::inner::Inner;
use super::policy::{LockerConfig, OnCorrupt, Policy};
use super::resident::{Pending, Resident};
use super::transaction::{Staged, Transaction, TxMode};
use crate::watch::Event;

/// An eager locker's resident values.
///
/// Named because it is shared, type-erased, through the bank's open-locker
/// registry, and the downcast back has to spell it exactly. See
/// [`crate::Bank::locker_with`].
pub(crate) type EagerValues<T> = Mutex<BTreeMap<Vec<u8>, Arc<T>>>;

/// A locker whose values live in memory. Hive's `Box`.
///
/// Every value is loaded at open and kept resident, which is what makes
/// [`Locker::get`] synchronous and infallible — the call a UI makes from a
/// path that cannot await. That bargain has a price, so
/// [`LockerConfig::eager_budget`] refuses to open a locker whose contents are
/// larger than you said they would be, rather than discovering it as an
/// out-of-memory abort later. For bulk data, use [`crate::LazyLocker`].
///
/// ```no_run
/// use crossbank::{Bank, BankConfig, Locker};
///
/// # async fn demo() -> crossbank::Result<()> {
/// let bank = Bank::open(BankConfig::at("app.crossbank")).await?;
/// let settings: Locker<String> = bank.locker("settings").await?;
///
/// // A durable commit by default: when this resolves, the data is on disk.
/// settings.put("theme", "dark".to_string()).await?;
///
/// // ...and reads never await and never fail.
/// assert_eq!(settings.get("theme").as_deref(), Some(&"dark".to_string()));
/// assert_eq!(*settings.get_or("accent", "blue".to_string()), "blue");
///
/// // Bulk work is one atomic commit, not one per pair.
/// settings.put_all(vec![("locale".to_string(), "en".to_string())]).await?;
/// settings.delete_all(vec!["locale".to_string()]).await?;
///
/// // `close` is async: it flushes first, so a bare `settings.close();`
/// // would be a dropped future that does nothing.
/// settings.close().await?;
/// # Ok(())
/// # }
/// ```
pub struct Locker<T> {
    inner: Arc<Inner>,
    /// Shared with the coherence sink, which replaces resident values from
    /// another tab's news without going through the locker handle — and with
    /// every other handle on this locker's name.
    values: Arc<EagerValues<T>>,
    /// Staged writes and the keys that would not decode, shared with
    /// [`crate::Bank::flush_all`], which cannot know `T`. An eager locker
    /// keeps no key index and takes no byte budget, so that is all this holds.
    res: Arc<Resident>,
}

impl<T> std::fmt::Debug for Locker<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Locker")
            .field("name", &self.inner.name)
            .field("entries", &self.len())
            .finish()
    }
}

impl<T> Locker<T>
where
    T: Serialize + DeserializeOwned,
{
    pub(crate) async fn open(
        backend: Arc<dyn Backend>,
        chain: Arc<FilterChain>,
        id: LockerId,
        name: String,
        config: LockerConfig,
        shared: Arc<super::inner::Shared>,
    ) -> Result<Self> {
        // Eviction and residency contradict each other: shedding a value from
        // storage while RAM still holds it leaves a replica that outlives the
        // eviction. Refuse the combination rather than paper over it.
        if let Policy::Evictable { .. } = config.policy {
            return Err(Error::InvalidConfig(format!(
                "locker {name:?} is eager, which cannot use an evictable policy; \
                 use a lazy locker instead"
            )));
        }

        let budget = config.eager_budget;
        let on_corrupt = config.on_corrupt;
        let inner = Arc::new(Inner {
            write_lock: futures::lock::Mutex::new(()),
            backend,
            chain,
            id,
            name,
            config,
            shared,
            watchers: Default::default(),
            closed: AtomicBool::new(false),
            epochs: Default::default(),
            name_shared: AtomicBool::new(false),
        });

        let mut values = BTreeMap::new();
        let mut corrupt: Vec<Vec<u8>> = Vec::new();
        let mut loaded: u64 = 0;
        let mut overflow: Option<u64> = None;

        inner
            .walk(
                Bound::Unbounded,
                Bound::Unbounded,
                false,
                true,
                |key, raw| {
                    let bytes = raw.ok_or_else(|| {
                        Error::Corrupt(format!("backend omitted a value for key {key:?}"))
                    })?;

                    loaded = loaded.saturating_add(bytes.len() as u64);
                    if loaded > budget {
                        // Record and keep walking rather than decoding further —
                        // the point is to fail before the memory is committed.
                        overflow.get_or_insert(loaded);
                        return Ok(());
                    }

                    match inner.open::<T>(&bytes) {
                        Ok(value) => {
                            values.insert(key, Arc::new(value));
                        }
                        // Skip records the decoder chokes on, when asked to.
                        // The stored bytes are left untouched, so a later
                        // build with a working decoder can still read them.
                        Err(e) if on_corrupt == OnCorrupt::Skip && e.is_corruption() => {
                            corrupt.push(key);
                        }
                        Err(e) => return Err(e),
                    }
                    Ok(())
                },
            )
            .await?;

        if overflow.is_some() {
            return Err(Error::LockerTooLarge {
                bytes: loaded,
                budget,
            });
        }

        let res = Arc::new(Resident::new(inner.clone(), TxMode::Eager, None, None));
        for key in corrupt {
            res.note_corrupt(&key);
        }
        Ok(Self {
            inner,
            values: Arc::new(Mutex::new(values)),
            res,
        })
    }

    /// A second handle onto a name this bank already has open.
    ///
    /// Every part of the locker's state is shared, so the two handles are two
    /// views of one open locker rather than two copies of it — which is what
    /// `Hive.box(name)` gives, and the only shape that cannot serve a stale
    /// read. Nothing is read from the backend: the first open already loaded
    /// the values and bound the type and the filter chain.
    pub(crate) fn from_shared(
        inner: Arc<Inner>,
        values: Arc<EagerValues<T>>,
        res: Arc<Resident>,
    ) -> Self {
        Self { inner, values, res }
    }

    /// Store a value. Writes are asynchronous even though reads are not.
    pub async fn put(&self, key: &str, value: T) -> Result<Arc<T>> {
        self.put_by(key.as_bytes(), value).await
    }

    /// As [`Locker::put`], under a binary key.
    pub async fn put_by(&self, key: &[u8], value: T) -> Result<Arc<T>> {
        self.inner.ensure_open()?;
        let sealed = self.inner.seal(&value)?;
        if sealed.len() > self.inner.config.max_inline {
            return Err(Error::ValueTooLarge {
                bytes: sealed.len(),
                max_inline: self.inner.config.max_inline,
            });
        }

        if self.res.is_deferred() {
            // The resident copy is updated at once: this handle's own writes
            // are visible to it immediately, committed or not. The payload is
            // re-encoded rather than reusing `sealed`, because the flush path
            // seals every batch through one code path.
            let payload = postcard::to_allocvec(&value)
                .map_err(|e| Error::Filter(format!("postcard serialisation failed: {e}")))?;
            let full = self.res.stage(Pending::Put {
                key: key.to_vec(),
                payload,
            })?;
            let shared = Arc::new(value);
            if let Ok(mut guard) = self.values.lock() {
                guard.insert(key.to_vec(), shared.clone());
            }
            self.res.forget_dropped(key);
            self.inner.announce(Event::Put { key: key.to_vec() });
            if full {
                let _guard = self.inner.write_lock.lock().await;
                self.res.flush_locked().await?;
            }
            return Ok(shared);
        }

        let op = crate::backend::api::Op::Put {
            table: crate::backend::api::Table::Records,
            key: self.inner.encode_key(key),
            value: sealed,
        };
        self.inner.commit(vec![op]).await?;

        // Only mirror into RAM after the write lands, so a failed commit does
        // not leave the resident copy claiming something that is not stored.
        let shared = Arc::new(value);
        if let Ok(mut guard) = self.values.lock() {
            guard.insert(key.to_vec(), shared.clone());
        }
        self.res.forget_dropped(key);
        self.inner.announce(Event::Put { key: key.to_vec() });
        Ok(shared)
    }

    /// Commit everything this locker has staged. See [`crate::Commit`].
    ///
    /// Always safe to call: an immediate-commit locker has nothing staged and
    /// returns at once.
    /// **A closed locker may still be flushed.** [`Locker::close`] keeps the
    /// batch when its own flush fails, so `pending()` stays honest and the
    /// caller can fix the cause and retry here. Every write still reports
    /// [`Error::Closed`].
    ///
    /// Under [`crate::Durability::Eventual`] this also forces the backend
    /// fsync, so one `flush` is the whole durability contract regardless of
    /// which of the two knobs the locker turned.
    pub async fn flush(&self) -> Result<()> {
        let staged = self.res.flush().await;
        let forced = self.inner.flush_backend().await;
        staged.and(forced)
    }

    /// How many writes are staged and not yet committed.
    ///
    /// Reads 0 if the staging lock has been poisoned by a panic in another
    /// thread; [`Locker::flush`] reports that as [`Error::Backend`] rather
    /// than silently doing nothing.
    pub fn pending(&self) -> usize {
        self.res.pending_len().unwrap_or(0)
    }

    /// Payload bytes staged and not yet committed. See [`Locker::pending`] for
    /// the poisoned-lock caveat.
    pub fn pending_bytes(&self) -> u64 {
        self.res.pending_bytes().unwrap_or(0)
    }

    /// Run a transaction: every staged write lands together, or none does.
    ///
    /// Returning `Err` rolls back — nothing is written and the resident copy
    /// is untouched.
    pub async fn transact<F, Fut>(&self, f: F) -> Result<()>
    where
        F: FnOnce(Transaction<T>) -> Fut,
        Fut: std::future::Future<Output = Result<()>>,
    {
        self.inner.ensure_open()?;
        let _guard = self.inner.write_lock.lock().await;

        let tx = Transaction::new(self.inner.clone());
        let staged = tx.staged_handle();
        f(tx).await?;

        let entries = {
            let mut guard = staged
                .lock()
                .map_err(|_| Error::backend("transaction lock was poisoned"))?;
            std::mem::take(&mut *guard)
        };
        if entries.is_empty() {
            return Ok(());
        }

        // Absorb anything this handle has staged under `Commit::Deferred`, so
        // both batches ride in one commit — staged first, transaction last.
        // Without this, a later flush would write the older staged value over
        // this transaction's newer one.
        let staged_before = self.res.take_staged()?;
        let merged = super::lazy::merge_batches(&staged_before, &entries);

        // An eager locker holds its values, so the size limit applies to
        // transactional writes exactly as it does to a plain put.
        // `ops_for_pending` enforces it while sealing, so the bytes are only
        // produced once.
        let ops =
            match super::transaction::ops_for_pending(&self.inner, &merged, TxMode::Eager).await {
                Ok(ops) => ops,
                Err(e) => {
                    self.res.restage(staged_before);
                    return Err(e);
                }
            };
        if let Err(e) = self.inner.commit(ops).await {
            self.res.restage(staged_before);
            return Err(e);
        }

        // A delete is only news if it took something away. Presence is
        // recorded as the map is mutated rather than beforehand, so a
        // put-then-delete of one key inside a single transaction still counts
        // as a real removal and a delete after a `Clear` does not. All-true if
        // the map is poisoned: announcing too much beats going quiet.
        let mut removed_something = vec![true; entries.len()];
        if let Ok(mut guard) = self.values.lock() {
            for (entry, removed) in entries.iter().zip(removed_something.iter_mut()) {
                match entry {
                    Staged::Put { key, value, .. } => {
                        guard.insert(key.clone(), value.clone());
                    }
                    Staged::Delete { key } => {
                        *removed = guard.remove(key).is_some() || self.res.stored_but_unheld(key);
                        self.res.forget_dropped(key);
                    }
                    Staged::Clear => {
                        guard.clear();
                        self.res.forget_all_dropped();
                    }
                }
            }
        }

        for (entry, removed) in entries.iter().zip(removed_something) {
            match entry {
                Staged::Put { key, .. } => self.inner.announce(Event::Put { key: key.clone() }),
                Staged::Delete { key } if removed => {
                    self.inner.announce(Event::Deleted { key: key.clone() })
                }
                Staged::Delete { .. } => {}
                Staged::Clear => self.inner.announce(Event::Cleared),
            }
        }
        Ok(())
    }

    /// Remove a key. Removing an absent key is not an error.
    ///
    /// **No [`Event::Deleted`] is announced for a key that was not there.**
    /// Hive fires only for keys that existed, and a `listenable(keys:)`-shaped
    /// rebuild driven off a spurious event repaints for nothing. An eager
    /// locker holds its values, so it can answer "was it there?" for free;
    /// [`crate::LazyLocker::delete`] cannot, and deliberately still announces
    /// unconditionally rather than paying a read to find out.
    pub async fn delete(&self, key: &str) -> Result<()> {
        self.delete_by(key.as_bytes()).await
    }

    /// As [`Locker::delete`], under a binary key.
    pub async fn delete_by(&self, key: &[u8]) -> Result<()> {
        self.inner.ensure_open()?;
        let held = self.holds(key);
        if !held && self.inner.index_is_authoritative() {
            // Nothing resident, and nothing this handle will never hear from
            // can have written a record here: no bytes to remove and no news
            // to carry. Where the map may *not* prove absence — a maintenance
            // locker, two banks over one backend, or a web tab with coherence
            // off — the delete still goes to storage, because a record left
            // behind is one whose chunks a later overwrite would orphan.
            return Ok(());
        }
        if self.res.is_deferred() {
            let full = self.res.stage(Pending::Delete { key: key.to_vec() })?;
            if let Ok(mut guard) = self.values.lock() {
                guard.remove(key);
            }
            self.res.forget_dropped(key);
            if held {
                self.inner.announce(Event::Deleted { key: key.to_vec() });
            }
            if full {
                let _guard = self.inner.write_lock.lock().await;
                self.res.flush_locked().await?;
            }
            return Ok(());
        }
        self.inner.commit(vec![self.inner.delete_op(key)]).await?;
        if let Ok(mut guard) = self.values.lock() {
            guard.remove(key);
        }
        self.res.forget_dropped(key);
        if held {
            self.inner.announce(Event::Deleted { key: key.to_vec() });
        }
        Ok(())
    }

    /// Whether this locker holds a record under `key`.
    ///
    /// A key the map does not hold the value of still counts when the record
    /// is stored: bytes skipped as corrupt at open, and a value another tab
    /// wrote that this one dropped as [`Event::Stale`]. Both are missing from
    /// the resident map while the record is very much on disk, so a delete
    /// must reach storage and really is news to anyone watching.
    fn holds(&self, key: &[u8]) -> bool {
        match self.values.lock() {
            Ok(guard) => guard.contains_key(key) || self.res.stored_but_unheld(key),
            // A poisoned map cannot prove absence. Behave as before.
            Err(_) => true,
        }
    }

    /// Store many entries in **one** atomic commit.
    ///
    /// Hive's `putAll`. Everything lands together or nothing does, which is
    /// both faster than N separate puts and the only way to write a set of
    /// keys that must stay consistent with each other.
    pub async fn put_all(&self, entries: impl IntoIterator<Item = (String, T)>) -> Result<()> {
        let entries: Vec<(String, T)> = entries.into_iter().collect();
        if entries.is_empty() {
            return Ok(());
        }
        self.transact(move |tx| async move {
            for (key, value) in entries {
                tx.put(&key, value)?;
            }
            Ok(())
        })
        .await
    }

    /// Remove many keys in **one** atomic commit. Hive's `deleteAll`.
    ///
    /// Removing an absent key is not an error, exactly as for
    /// [`Locker::delete`], and exactly as there it announces nothing: a
    /// `delete_all` over a hundred keys of which two existed is two events,
    /// not a hundred.
    pub async fn delete_all(&self, keys: impl IntoIterator<Item = impl AsRef<str>>) -> Result<()> {
        let keys: Vec<String> = keys.into_iter().map(|k| k.as_ref().to_string()).collect();
        if keys.is_empty() {
            return Ok(());
        }
        self.transact(move |tx| async move {
            for key in keys {
                tx.delete(&key)?;
            }
            Ok(())
        })
        .await
    }

    /// Remove everything in this locker, and nothing outside it.
    pub async fn clear(&self) -> Result<()> {
        self.inner.ensure_open()?;
        if self.res.is_deferred() {
            let full = self.res.stage(Pending::Clear)?;
            if let Ok(mut guard) = self.values.lock() {
                guard.clear();
            }
            self.res.forget_all_dropped();
            self.inner.announce(Event::Cleared);
            if full {
                let _guard = self.inner.write_lock.lock().await;
                self.res.flush_locked().await?;
            }
            return Ok(());
        }
        self.inner.commit(vec![self.inner.clear_op()]).await?;
        if let Ok(mut guard) = self.values.lock() {
            guard.clear();
        }
        self.res.forget_all_dropped();
        self.inner.announce(Event::Cleared);
        Ok(())
    }
}

/// Applies another tab's news to one open eager locker.
///
/// Generic over `T` because an eager locker holds decoded values: replacing
/// one means decoding the bytes the message carried.
#[cfg_attr(not(target_arch = "wasm32"), allow(dead_code))]
pub(crate) struct EagerSink<T> {
    inner: Arc<Inner>,
    values: Arc<Mutex<BTreeMap<Vec<u8>, Arc<T>>>>,
    /// Weak for the reason `LazySink`'s is: the resident state owns the sink,
    /// so a strong reference back would be a cycle that keeps the locker, its
    /// `Inner` and the backend handle alive forever — on the web, an
    /// IndexedDB connection that never closes.
    res: std::sync::Weak<Resident>,
}

#[cfg_attr(not(target_arch = "wasm32"), allow(dead_code))]
impl<T: DeserializeOwned> crate::coherence::Sink for EagerSink<T> {
    fn locker_id(&self) -> LockerId {
        self.inner.id
    }

    fn apply(&self, announcement: &crate::coherence::Announcement) {
        if self.inner.is_closed() {
            return;
        }
        // A message this tab has already absorbed, or one from a tab whose
        // clock is behind news already applied, tells it nothing new.
        if announcement.epoch <= self.inner.epochs.applied() {
            return;
        }
        self.inner.epochs.note_applied(announcement.epoch);

        let res = self.res.upgrade();
        if announcement.cleared {
            if let Ok(mut values) = self.values.lock() {
                values.clear();
            }
            if let Some(res) = res.as_ref() {
                res.forget_all_dropped();
            }
            self.inner.epochs.forget_local();
            self.inner.announce(Event::Cleared);
        }
        for change in &announcement.changes {
            // This tab's own commit for that key is at least as new, so the
            // message would be undoing a write this tab has already made. See
            // `BankConfig::coherence` for exactly what this does and does not
            // order.
            if self
                .inner
                .epochs
                .local(&change.key)
                .is_some_and(|mine| announcement.epoch <= mine)
            {
                continue;
            }

            // Decoded here, in a plain callback, so `get()` stays synchronous
            // and infallible. What cannot be decoded here cannot be held.
            let decoded = match (change.deleted, &change.value) {
                (true, _) => None,
                (false, Some(sealed)) => self.inner.open::<T>(sealed).ok().map(Arc::new),
                (false, None) => None,
            };

            let event = match (&decoded, change.deleted) {
                (Some(_), _) => Event::Put {
                    key: change.key.clone(),
                },
                (None, true) => Event::Deleted {
                    key: change.key.clone(),
                },
                // The key was written, but with a value this tab cannot hold:
                // too large to carry, or bytes it cannot decode. Dropping the
                // resident copy is the honest answer — a stale value would be
                // a lie an infallible getter could not take back.
                (None, false) => Event::Stale {
                    key: change.key.clone(),
                },
            };

            if let Ok(mut values) = self.values.lock() {
                match decoded {
                    Some(value) => {
                        values.insert(change.key.clone(), value);
                    }
                    None => {
                        values.remove(change.key.as_slice());
                    }
                }
            }
            // A stale key is one this tab no longer holds a value for while
            // the record is still stored — so it has to keep counting as
            // *present*, or `delete` would decide there was nothing to remove
            // and return `Ok(())` having written nothing. Remembering it is
            // what makes the two tabs' stores agree again.
            if let Some(res) = res.as_ref() {
                match event {
                    Event::Stale { .. } => res.note_dropped(&change.key),
                    _ => res.forget_dropped(&change.key),
                }
            }
            self.inner.announce(event);
        }
    }
}

/// Bounds-free accessors. Split out so `Debug` — and any caller holding a
/// `Locker<T>` for a `T` that is not itself serialisable — can still read.
impl<T> Locker<T> {
    #[cfg_attr(not(target_arch = "wasm32"), allow(dead_code))]
    pub(crate) fn sink(&self) -> EagerSink<T> {
        EagerSink {
            inner: self.inner.clone(),
            values: self.values.clone(),
            res: Arc::downgrade(&self.res),
        }
    }
}

impl<T: DeserializeOwned + 'static> Locker<T> {
    /// Start receiving other tabs' news. See [`LazyLocker::join_coherence`].
    pub(crate) fn join_coherence(&self) {
        #[cfg(target_arch = "wasm32")]
        {
            self.res
                .join_coherence(|| crate::coherence::handle(self.sink()));
        }
    }
}

impl<T> Locker<T> {
    pub fn name(&self) -> &str {
        &self.inner.name
    }

    pub(crate) fn inner(&self) -> &Arc<Inner> {
        &self.inner
    }

    pub(crate) fn resident(&self) -> &Arc<Resident> {
        &self.res
    }

    /// The resident map, for the bank to hand to the next handle on this name.
    pub(crate) fn shared_values(&self) -> &Arc<EagerValues<T>> {
        &self.values
    }

    /// Keys whose stored bytes would not decode when this locker was opened.
    ///
    /// Always empty under [`OnCorrupt::Fail`], which refuses to open at all
    /// rather than reporting a partial view. Under [`OnCorrupt::Skip`] these
    /// are exactly the keys missing from [`Locker::keys`] and [`Locker::len`];
    /// their bytes are still on disk, untouched. [`crate::Bank::quarantine`]
    /// is the only thing that removes them.
    pub fn corrupt_keys(&self) -> Vec<Vec<u8>> {
        self.res.corrupt_keys()
    }

    /// Close this locker: drop its resident values and refuse further writes.
    ///
    /// The **bank's** backend is left open — closing one locker must not take
    /// the store down with it. Use [`crate::Bank::close`] for that.
    ///
    /// After this, [`Locker::get`] returns `None` and [`Locker::len`] is 0 for
    /// every key, exactly as if the locker were empty. That is not a lie the
    /// caller has to live with: [`Locker::is_closed`] is what distinguishes a
    /// closed locker from an empty one. Writes report [`Error::Closed`]
    /// instead of silently succeeding.
    ///
    /// Idempotent, and it does not delete anything — reopening the same name
    /// from the bank finds the data untouched.
    pub async fn close(&self) -> Result<()> {
        // Flush before closing, and close even if the flush fails: a caller
        // who is shutting down must not be left holding an open locker just
        // because its last batch would not land.
        let flushed = self.res.flush().await;
        // Only discard once the batch is actually stored — a failed flush has
        // written nothing, and this buffer is the only copy of it.
        if flushed.is_ok() {
            self.res.discard_staged();
        }
        // Separate from the staged flush on purpose: the discard above must
        // key off whether the *batch* landed, not off whether a later fsync
        // succeeded, or a retry would write it twice.
        let forced = self.inner.flush_backend().await;
        self.inner.mark_closed();
        if let Ok(mut guard) = self.values.lock() {
            guard.clear();
        }
        flushed.and(forced)
    }

    /// Whether [`Locker::close`] has been called.
    ///
    /// The only way to tell a closed locker from an empty one, since a closed
    /// locker reads as empty by design.
    pub fn is_closed(&self) -> bool {
        self.inner.is_closed()
    }

    /// Read a value. Synchronous and infallible — the whole point of the type.
    pub fn get(&self, key: &str) -> Option<Arc<T>> {
        self.get_by(key.as_bytes())
    }

    /// As [`Locker::get`], under a binary key.
    pub fn get_by(&self, key: &[u8]) -> Option<Arc<T>> {
        self.values.lock().ok()?.get(key).cloned()
    }

    /// Read a value by cloning it out of the resident copy.
    ///
    /// [`Locker::get`] hands back an `Arc` and asks nothing of `T`; this is
    /// for callers who would rather own a `T` than reach through a pointer.
    pub fn get_cloned(&self, key: &str) -> Option<T>
    where
        T: Clone,
    {
        self.get(key).map(|v| (*v).clone())
    }

    /// Read a value, falling back to `default` when the key is absent.
    ///
    /// Hive's `get(key, defaultValue:)`. The default is *not* written — a read
    /// stays a read.
    pub fn get_or(&self, key: &str, default: T) -> Arc<T> {
        self.get(key).unwrap_or_else(|| Arc::new(default))
    }

    /// Run `f` over the stored value without cloning it or handing out an
    /// `Arc`. `None` when the key is absent.
    ///
    /// The lock is **not** held while `f` runs, so `f` may call back into this
    /// locker without deadlocking.
    pub fn with<R>(&self, key: &str, f: impl FnOnce(&T) -> R) -> Option<R> {
        let value = self.get(key)?;
        Some(f(&value))
    }

    pub fn contains_key(&self, key: &str) -> bool {
        self.contains_key_by(key.as_bytes())
    }

    /// As [`Locker::contains_key`], under a binary key.
    pub fn contains_key_by(&self, key: &[u8]) -> bool {
        self.values
            .lock()
            .map(|v| v.contains_key(key))
            .unwrap_or(false)
    }

    pub fn len(&self) -> usize {
        self.values.lock().map(|v| v.len()).unwrap_or(0)
    }

    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Every UTF-8 key, in byte order.
    ///
    /// Keys that are not valid UTF-8 are **skipped**, not reported as an
    /// error — a listing must never fail because of a key it cannot spell.
    /// [`Locker::has_non_utf8_keys`] says whether any were skipped, and
    /// [`Locker::keys_bytes`] returns every key regardless.
    /// Keys are **bytes**, so the `&str` listings skip what they cannot spell
    /// rather than failing. [`Locker::has_non_utf8_keys`] says whether
    /// anything was skipped and [`Locker::keys_bytes`] returns all of them.
    ///
    /// ```no_run
    /// use crossbank::{Bank, BankConfig, Locker};
    ///
    /// # async fn demo() -> crossbank::Result<()> {
    /// let bank = Bank::open(BankConfig::at("app.crossbank")).await?;
    /// let settings: Locker<String> = bank.locker("settings").await?;
    ///
    /// for key in settings.keys() {
    ///     println!("{key}");
    /// }
    /// if settings.has_non_utf8_keys() {
    ///     println!("{} keys in total", settings.keys_bytes().len());
    /// }
    /// for key in settings.keys_with_prefix("theme_") {
    ///     println!("theme variant: {key}");
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub fn keys(&self) -> Vec<String> {
        self.values
            .lock()
            .map(|v| v.keys().filter_map(|k| super::lazy::utf8(k)).collect())
            .unwrap_or_default()
    }

    /// Every key as raw bytes, in byte order. Includes non-UTF-8 keys.
    pub fn keys_bytes(&self) -> Vec<Vec<u8>> {
        self.values
            .lock()
            .map(|v| v.keys().cloned().collect())
            .unwrap_or_default()
    }

    /// Whether this locker holds any key that [`Locker::keys`] cannot return.
    /// Never panics and never errors.
    pub fn has_non_utf8_keys(&self) -> bool {
        self.values
            .lock()
            .map(|v| v.keys().any(|k| std::str::from_utf8(k).is_err()))
            .unwrap_or(false)
    }

    /// Keys beginning with `prefix`, in byte order. UTF-8 keys only.
    pub fn keys_with_prefix(&self, prefix: &str) -> Vec<String> {
        self.keys_with_prefix_by(prefix.as_bytes())
            .iter()
            .filter_map(|k| super::lazy::utf8(k))
            .collect()
    }

    /// As [`Locker::keys_with_prefix`], over a binary prefix.
    pub fn keys_with_prefix_by(&self, prefix: &[u8]) -> Vec<Vec<u8>> {
        self.values
            .lock()
            .map(|v| {
                v.range(prefix.to_vec()..)
                    .take_while(|(k, _)| k.starts_with(prefix))
                    .map(|(k, _)| k.clone())
                    .collect()
            })
            .unwrap_or_default()
    }

    /// Subscribe to every change in this locker.
    pub fn watch(&self) -> crate::watch::EventStream {
        self.inner
            .watchers
            .subscribe(None, crate::watch::DEFAULT_CAPACITY)
    }

    /// Subscribe to changes affecting any of `keys`.
    ///
    /// Hive's `listenable(keys:)`. `Cleared` and `Lagged` always arrive: a
    /// clear affects every key, and a gap notice must never be dropped. An
    /// empty list therefore yields a stream of nothing but those two.
    pub fn watch_keys(&self, keys: &[&str]) -> crate::watch::EventStream {
        self.inner.watchers.subscribe(
            Some(keys.iter().map(|k| k.as_bytes().to_vec()).collect()),
            crate::watch::DEFAULT_CAPACITY,
        )
    }

    /// Subscribe to changes affecting one key.
    ///
    /// `Cleared` still arrives, because a clear affects every key.
    pub fn watch_key(&self, key: &str) -> crate::watch::EventStream {
        self.inner.watchers.subscribe(
            Some(vec![key.as_bytes().to_vec()]),
            crate::watch::DEFAULT_CAPACITY,
        )
    }

    /// Entries over a key range, in byte order. UTF-8 keys only.
    ///
    /// Synchronous, like every other eager read: the values are already here.
    pub fn range<'a, R: std::ops::RangeBounds<&'a str>>(&self, range: R) -> Vec<(String, Arc<T>)> {
        let start = crate::key::as_bytes(str_bound(range.start_bound()));
        let end = crate::key::as_bytes(str_bound(range.end_bound()));
        // `BTreeMap::range` *panics* on an inverted or empty-by-exclusion
        // range, and a wasm release build turns that into an abort.
        if crate::key::is_degenerate(start, end) {
            return Vec::new();
        }
        self.values
            .lock()
            .map(|v| {
                v.range::<[u8], _>((start, end))
                    .filter_map(|(k, val)| super::lazy::utf8(k).map(|k| (k, val.clone())))
                    .collect()
            })
            .unwrap_or_default()
    }

    /// Every entry as a map, in byte order. UTF-8 keys only.
    ///
    /// Hive's `toMap`. Free of I/O — an eager locker already holds everything.
    pub fn to_map(&self) -> BTreeMap<String, Arc<T>> {
        self.entries().into_iter().collect()
    }

    /// A snapshot of every entry, in byte order. UTF-8 keys only.
    pub fn entries(&self) -> Vec<(String, Arc<T>)> {
        self.values
            .lock()
            .map(|v| {
                v.iter()
                    .filter_map(|(k, val)| super::lazy::utf8(k).map(|k| (k, val.clone())))
                    .collect()
            })
            .unwrap_or_default()
    }

    /// A snapshot of every entry as raw key bytes, in byte order.
    pub fn entries_bytes(&self) -> Vec<(Vec<u8>, Arc<T>)> {
        self.values
            .lock()
            .map(|v| v.iter().map(|(k, val)| (k.clone(), val.clone())).collect())
            .unwrap_or_default()
    }
}

/// `Range<&str>` bounds arrive as `Bound<&&str>`; unwrap the extra reference.
fn str_bound<'a>(bound: Bound<&&'a str>) -> Bound<&'a str> {
    match bound {
        Bound::Unbounded => Bound::Unbounded,
        Bound::Included(s) => Bound::Included(s),
        Bound::Excluded(s) => Bound::Excluded(s),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::backend::MemoryBackend;
    use crate::codec::default_chain;
    use crate::coherence::{api::Change, Announcement, Sink};
    use futures::executor::block_on;
    use futures::StreamExt;

    fn open_with(config: LockerConfig) -> Result<Locker<String>> {
        block_on(Locker::open(
            Arc::new(MemoryBackend::new()),
            Arc::new(default_chain()),
            1,
            "test".into(),
            config,
            Default::default(),
        ))
    }

    fn locker() -> Locker<String> {
        open_with(LockerConfig::default()).unwrap()
    }

    /// An eager locker takes another tab's small write straight into RAM.
    #[test]
    fn a_sink_replaces_a_resident_value_from_an_inline_write() {
        let l = locker();
        block_on(l.put("k", "mine".into())).unwrap();
        let mut events = l.watch();

        let sealed = l.inner.seal(&"theirs".to_string()).unwrap();
        l.sink().apply(&Announcement {
            instance: 2,
            locker_id: l.inner.id,
            epoch: 1,
            cleared: false,
            changes: vec![Change {
                key: b"k".to_vec(),
                value: Some(sealed),
                bytes: None,
                deleted: false,
            }],
        });

        assert_eq!(l.get("k").as_deref(), Some(&"theirs".to_string()));
        assert_eq!(events.try_recv(), Some(Event::Put { key: b"k".to_vec() }));
    }

    /// A write too large to carry drops the resident copy and says so.
    ///
    /// The alternative — keeping the old value — would make an infallible
    /// getter hand back something the store no longer holds, with nothing to
    /// tell the caller. `None` plus [`Event::Stale`] is the honest answer.
    #[test]
    fn a_write_it_cannot_hold_goes_stale_rather_than_lying() {
        let l = locker();
        block_on(l.put("k", "mine".into())).unwrap();
        let mut events = l.watch();

        l.sink().apply(&Announcement {
            instance: 2,
            locker_id: l.inner.id,
            epoch: 1,
            cleared: false,
            changes: vec![Change {
                key: b"k".to_vec(),
                value: None,
                bytes: None,
                deleted: false,
            }],
        });

        assert_eq!(l.get("k"), None, "a value we cannot decode is not held");
        assert_eq!(events.try_recv(), Some(Event::Stale { key: b"k".to_vec() }));
    }

    /// A key dropped as stale can still be deleted.
    ///
    /// `delete` short-circuits when the resident map does not hold the key and
    /// the index is authoritative: nothing resident, nothing stored, nothing
    /// to do. A stale key breaks that reasoning — the record *is* stored, it
    /// is only this tab's copy that is gone — so the short circuit turned a
    /// user's delete into a silent no-op, and the record came back at the next
    /// reopen. `delete_all` went through `transact` and wrote the op, so the
    /// two spellings of one operation disagreed.
    #[test]
    fn a_key_dropped_as_stale_is_still_deleted() {
        let backend = Arc::new(MemoryBackend::new());
        let l: Locker<String> = block_on(Locker::open(
            backend.clone(),
            Arc::new(default_chain()),
            1,
            "test".into(),
            LockerConfig::default(),
            Default::default(),
        ))
        .unwrap();
        block_on(l.put("session", "mine".into())).unwrap();
        let stored = l.inner.encode_key(b"session");
        assert!(
            block_on(backend.get(crate::backend::api::Table::Records, &stored))
                .unwrap()
                .is_some()
        );

        // Another tab wrote a value this one cannot carry: the resident copy
        // goes, the record stays.
        l.sink().apply(&Announcement {
            instance: 2,
            locker_id: l.inner.id,
            epoch: 1,
            cleared: false,
            changes: vec![Change {
                key: b"session".to_vec(),
                value: None,
                bytes: None,
                deleted: false,
            }],
        });
        assert_eq!(l.get("session"), None, "the resident copy is gone");

        let mut events = l.watch();
        block_on(l.delete("session")).unwrap();

        assert_eq!(
            block_on(backend.get(crate::backend::api::Table::Records, &stored)).unwrap(),
            None,
            "the delete must reach storage: the record was still there"
        );
        assert_eq!(
            events.try_recv(),
            Some(Event::Deleted {
                key: b"session".to_vec()
            }),
            "and it really took something away, so it is news"
        );
    }

    fn one_change(id: LockerId, epoch: u64, key: &[u8], sealed: Option<Vec<u8>>) -> Announcement {
        Announcement {
            instance: 2,
            locker_id: id,
            epoch,
            cleared: false,
            changes: vec![Change {
                key: key.to_vec(),
                value: sealed,
                bytes: None,
                deleted: false,
            }],
        }
    }

    /// The epoch on an announcement must actually be used.
    ///
    /// It was decoded and thrown away, so a message that arrived twice, or
    /// out of order behind a newer one, was replayed over the resident copy
    /// and the locker ended up holding an older value than it had already
    /// absorbed.
    #[test]
    fn a_sink_ignores_an_announcement_it_has_already_overtaken() {
        let l = locker();
        let id = l.inner.id;
        let sink = l.sink();

        let newer = l.inner.seal(&"newer".to_string()).unwrap();
        let older = l.inner.seal(&"older".to_string()).unwrap();

        sink.apply(&one_change(id, 5, b"k", Some(newer)));
        assert_eq!(l.get("k").as_deref(), Some(&"newer".to_string()));

        // Same epoch again — a duplicate delivery.
        sink.apply(&one_change(id, 5, b"k", Some(older.clone())));
        assert_eq!(
            l.get("k").as_deref(),
            Some(&"newer".to_string()),
            "a duplicate epoch must not be replayed"
        );

        // And an older one, arriving late.
        sink.apply(&one_change(id, 3, b"k", Some(older)));
        assert_eq!(
            l.get("k").as_deref(),
            Some(&"newer".to_string()),
            "an out-of-order older epoch must not overwrite a newer one"
        );

        // A genuinely newer one still lands.
        let newest = l.inner.seal(&"newest".to_string()).unwrap();
        sink.apply(&one_change(id, 9, b"k", Some(newest)));
        assert_eq!(l.get("k").as_deref(), Some(&"newest".to_string()));
    }

    /// This tab's own committed write outranks another tab's older news for
    /// the same key, so a message already in flight cannot undo it.
    #[test]
    fn a_sink_will_not_undo_this_tabs_own_newer_commit() {
        let l = locker();
        let id = l.inner.id;
        // Natively no announcement is produced, so record the marker the way
        // a commit under coherence would.
        l.inner.epochs.note_local([b"k".to_vec()].into_iter(), 7);
        block_on(l.put("k", "mine".into())).unwrap();

        let theirs = l.inner.seal(&"theirs".to_string()).unwrap();
        l.sink()
            .apply(&one_change(id, 7, b"k", Some(theirs.clone())));
        assert_eq!(
            l.get("k").as_deref(),
            Some(&"mine".to_string()),
            "an equal epoch must not undo this tab's own commit"
        );

        l.sink().apply(&one_change(id, 8, b"k", Some(theirs)));
        assert_eq!(
            l.get("k").as_deref(),
            Some(&"theirs".to_string()),
            "a strictly newer epoch still wins"
        );
    }

    #[test]
    fn get_is_synchronous_and_returns_what_was_put() {
        let l = locker();
        block_on(l.put("theme", "dark".into())).unwrap();
        // No await here. That is the feature.
        assert_eq!(l.get("theme").as_deref(), Some(&"dark".to_string()));
    }

    #[test]
    fn a_missing_key_is_none() {
        let l = locker();
        assert!(l.get("nope").is_none());
    }

    #[test]
    fn overwriting_replaces() {
        let l = locker();
        block_on(l.put("k", "first".into())).unwrap();
        block_on(l.put("k", "second".into())).unwrap();
        assert_eq!(l.get("k").as_deref(), Some(&"second".to_string()));
        assert_eq!(l.len(), 1);
    }

    #[test]
    fn delete_removes_from_ram_and_storage() {
        let l = locker();
        block_on(l.put("k", "v".into())).unwrap();
        block_on(l.delete("k")).unwrap();
        assert!(l.get("k").is_none());
        assert_eq!(l.len(), 0);
    }

    /// Hive fires a box event only for keys that were really there. A
    /// `listenable(keys:)`-shaped rebuild driven off a spurious `Deleted`
    /// repaints for nothing, so an absent key must be silent.
    #[test]
    fn deleting_an_absent_key_is_silent() {
        let l = locker();
        block_on(l.put("here", "v".into())).unwrap();
        let mut events = l.watch();

        block_on(l.delete("gone")).unwrap();
        assert_eq!(
            events.try_recv(),
            None,
            "a key that was never there is not news"
        );

        block_on(l.delete("here")).unwrap();
        assert_eq!(
            events.try_recv(),
            Some(Event::Deleted {
                key: b"here".to_vec()
            })
        );
        assert_eq!(events.try_recv(), None, "exactly one event, not two");

        // And a second delete of the same key is silent in its turn.
        block_on(l.delete("here")).unwrap();
        assert_eq!(events.try_recv(), None);
    }

    /// `delete_all` runs through `transact`, so the same rule has to hold
    /// there — and it is where the spurious events came in bulk.
    #[test]
    fn delete_all_announces_only_the_keys_it_took_away() {
        let l = locker();
        block_on(l.put("a", "1".into())).unwrap();
        block_on(l.put("c", "3".into())).unwrap();
        let mut events = l.watch();

        block_on(l.delete_all(["a", "b", "c", "d"])).unwrap();

        assert_eq!(
            events.try_recv(),
            Some(Event::Deleted { key: b"a".to_vec() })
        );
        assert_eq!(
            events.try_recv(),
            Some(Event::Deleted { key: b"c".to_vec() })
        );
        assert_eq!(events.try_recv(), None, "b and d were never there");
        assert_eq!(l.len(), 0);
    }

    /// Deferred staging takes the same route, and stages nothing for a key it
    /// does not hold.
    #[test]
    fn a_deferred_delete_of_an_absent_key_stages_nothing() {
        let l =
            open_with(LockerConfig::default().with_commit(crate::Commit::Deferred { after: 64 }))
                .unwrap();
        block_on(l.put("here", "v".into())).unwrap();
        let mut events = l.watch();
        let staged = l.pending();

        block_on(l.delete("gone")).unwrap();
        assert_eq!(events.try_recv(), None);
        assert_eq!(l.pending(), staged, "nothing was staged for an absent key");
    }

    /// The one key an eager locker does not hold and must still delete.
    ///
    /// Under `OnCorrupt::Skip` a damaged record is missing from the resident
    /// map while its bytes sit on disk untouched. Reading presence off the map
    /// alone would leave it there forever — and a later write of the same key
    /// would then orphan its chunks.
    #[test]
    fn deleting_a_corrupt_skipped_key_still_removes_the_record() {
        use crate::backend::api::{Backend, Op, Table};
        use crate::locker::OnCorrupt;

        let backend: Arc<dyn Backend> = Arc::new(MemoryBackend::new());
        let stored = crate::key::encode(1, "bad");
        block_on(backend.commit(vec![Op::Put {
            table: Table::Records,
            key: stored.clone(),
            value: b"not a CBNK envelope".to_vec(),
        }]))
        .unwrap();

        let l: Locker<String> = block_on(Locker::open(
            backend.clone(),
            Arc::new(default_chain()),
            1,
            "test".into(),
            LockerConfig::default().with_on_corrupt(OnCorrupt::Skip),
            Default::default(),
        ))
        .unwrap();
        assert_eq!(l.corrupt_keys(), vec![b"bad".to_vec()]);
        assert!(l.get("bad").is_none(), "skipped, so not resident");

        let mut events = l.watch();
        block_on(l.delete("bad")).unwrap();

        assert!(
            block_on(backend.get(Table::Records, &stored))
                .unwrap()
                .is_none(),
            "the corrupt bytes must really go"
        );
        assert_eq!(
            events.try_recv(),
            Some(Event::Deleted {
                key: b"bad".to_vec()
            }),
            "a record that was there really did go away"
        );
    }

    #[test]
    fn a_transaction_updates_ram_only_after_it_commits() {
        let l = locker();
        block_on(l.transact(|tx| async move {
            tx.put("a", "1".to_string())?;
            tx.put("b", "2".to_string())?;
            Ok(())
        }))
        .unwrap();

        assert_eq!(l.len(), 2);
        assert_eq!(l.get("a").as_deref(), Some(&"1".to_string()));
    }

    #[test]
    fn a_failed_transaction_leaves_the_resident_copy_alone() {
        let l = locker();
        block_on(l.put("existing", "old".into())).unwrap();

        let outcome: Result<()> = block_on(l.transact(|tx| async move {
            tx.put("a", "1".to_string())?;
            Err(Error::backend("nope"))
        }));
        assert!(outcome.is_err());

        assert!(l.get("a").is_none());
        assert_eq!(l.get("existing").as_deref(), Some(&"old".to_string()));
        assert_eq!(l.len(), 1);
    }

    #[test]
    fn a_transaction_respects_the_inline_size_limit() {
        // The limit must not be bypassable by routing a write through a
        // transaction instead of put().
        let l = open_with(LockerConfig::default().with_max_inline(64)).unwrap();

        let outcome: Result<()> = block_on(l.transact(|tx| async move {
            tx.put("big", "x".repeat(10_000))?;
            Ok(())
        }));

        assert!(matches!(outcome, Err(Error::ValueTooLarge { .. })));
        assert!(l.get("big").is_none());
    }

    #[test]
    fn an_eager_locker_announces_its_writes() {
        let l = locker();
        let mut events = l.watch();

        block_on(l.put("theme", "dark".into())).unwrap();

        assert_eq!(
            block_on(events.next()),
            Some(crate::watch::Event::Put {
                key: "theme".into()
            })
        );
    }

    #[test]
    fn keys_are_ordered_and_prefix_filtering_stops_at_the_boundary() {
        let l = locker();
        for k in ["ui::b", "ui::a", "uj::a"] {
            block_on(l.put(k, "v".into())).unwrap();
        }
        assert_eq!(l.keys(), vec!["ui::a", "ui::b", "uj::a"]);
        assert_eq!(l.keys_with_prefix("ui::"), vec!["ui::a", "ui::b"]);
    }

    #[test]
    fn an_oversized_value_is_refused_and_names_the_alternative() {
        let l = open_with(LockerConfig::default().with_max_inline(64)).unwrap();
        let big = "x".repeat(10_000);

        match block_on(l.put("big", big)) {
            Err(Error::ValueTooLarge { max_inline, .. }) => {
                assert_eq!(max_inline, 64);
            }
            other => panic!("expected ValueTooLarge, got {other:?}"),
        }
        // And it must not have half-landed.
        assert!(l.get("big").is_none());
    }

    #[test]
    fn an_evictable_policy_is_refused_at_open() {
        // Eviction plus residency would leave a RAM replica surviving the
        // eviction, so the combination is rejected rather than reconciled.
        let config = LockerConfig::default().with_policy(Policy::Evictable { max_bytes: 1024 });
        match open_with(config) {
            Err(Error::InvalidConfig(msg)) => {
                assert!(msg.contains("lazy locker"), "should name the fix: {msg}")
            }
            other => panic!("expected InvalidConfig, got {other:?}"),
        }
    }

    #[test]
    fn reopening_restores_every_value() {
        let backend: Arc<dyn Backend> = Arc::new(MemoryBackend::new());
        let chain = Arc::new(default_chain());

        let first: Locker<String> = block_on(Locker::open(
            backend.clone(),
            chain.clone(),
            1,
            "l".into(),
            LockerConfig::default(),
            Default::default(),
        ))
        .unwrap();
        block_on(first.put("a", "alpha".into())).unwrap();
        block_on(first.put("b", "beta".into())).unwrap();
        drop(first);

        let second: Locker<String> = block_on(Locker::open(
            backend,
            chain,
            1,
            "l".into(),
            LockerConfig::default(),
            Default::default(),
        ))
        .unwrap();
        assert_eq!(second.len(), 2);
        assert_eq!(second.get("a").as_deref(), Some(&"alpha".to_string()));
    }

    #[test]
    fn opening_over_too_much_data_fails_loudly() {
        // The guardrail against typing locker() where lazy_locker() was meant.
        let backend: Arc<dyn Backend> = Arc::new(MemoryBackend::new());
        let chain = Arc::new(default_chain());

        let seed: Locker<String> = block_on(Locker::open(
            backend.clone(),
            chain.clone(),
            1,
            "l".into(),
            LockerConfig::default(),
            Default::default(),
        ))
        .unwrap();
        for i in 0..50 {
            block_on(seed.put(&format!("k{i:03}"), "x".repeat(200))).unwrap();
        }
        drop(seed);

        let reopened: Result<Locker<String>> = block_on(Locker::open(
            backend,
            chain,
            1,
            "l".into(),
            LockerConfig::default().with_eager_budget(1024),
            Default::default(),
        ));

        match reopened {
            Err(Error::LockerTooLarge { budget, .. }) => assert_eq!(budget, 1024),
            other => panic!("expected LockerTooLarge, got {:?}", other.map(|_| "ok")),
        }
    }

    #[test]
    fn clear_empties_ram_and_storage() {
        let l = locker();
        block_on(l.put("a", "1".into())).unwrap();
        block_on(l.clear()).unwrap();
        assert_eq!(l.len(), 0);
        assert!(l.get("a").is_none());
    }

    #[test]
    fn binary_keys_live_alongside_text_ones() {
        let l = locker();
        block_on(l.put_by(&[0xFF], "high".into())).unwrap();
        block_on(l.put_by(&[0x00], "low".into())).unwrap();
        block_on(l.put("a", "text".into())).unwrap();

        assert_eq!(l.get_by(&[0xFF]).as_deref(), Some(&"high".to_string()));
        assert!(l.contains_key_by(&[0x00]));
        assert_eq!(
            l.keys_bytes(),
            vec![vec![0x00], b"a".to_vec(), vec![0xFF]],
            "keys must be ordered bytewise"
        );
        // The str listing skips what it cannot spell, and admits to it. Note
        // 0x00 IS valid UTF-8 (a NUL string), so it survives the filter.
        assert_eq!(l.keys(), vec!["\u{0}".to_string(), "a".to_string()]);
        assert!(l.has_non_utf8_keys());

        block_on(l.delete_by(&[0xFF])).unwrap();
        assert!(l.get_by(&[0xFF]).is_none());
        assert_eq!(l.len(), 2);
    }

    #[test]
    fn a_locker_of_text_keys_reports_no_binary_ones() {
        let l = locker();
        block_on(l.put("a", "1".into())).unwrap();
        assert!(!l.has_non_utf8_keys());
        assert_eq!(l.keys_bytes(), vec![b"a".to_vec()]);
    }

    #[test]
    fn get_ergonomics_cover_clone_default_and_borrow() {
        let l = locker();
        block_on(l.put("theme", "dark".into())).unwrap();

        assert_eq!(l.get_cloned("theme"), Some("dark".to_string()));
        assert_eq!(l.get_cloned("absent"), None);

        assert_eq!(*l.get_or("theme", "light".into()), "dark".to_string());
        assert_eq!(*l.get_or("absent", "light".into()), "light".to_string());
        // The default is a read-time fallback, never a write.
        assert!(!l.contains_key("absent"));

        assert_eq!(l.with("theme", |v| v.len()), Some(4));
        assert_eq!(l.with("absent", |v| v.len()), None);
    }

    #[test]
    fn put_all_lands_as_one_commit() {
        let l = locker();
        let entries: Vec<(String, String)> = (0..50)
            .map(|i| (format!("k{i:03}"), format!("v{i}")))
            .collect();
        block_on(l.put_all(entries)).unwrap();

        assert_eq!(l.len(), 50);
        assert_eq!(l.get("k049").as_deref(), Some(&"v49".to_string()));

        block_on(l.delete_all(["k000", "k001"])).unwrap();
        assert_eq!(l.len(), 48);
        assert!(l.get("k000").is_none());
    }

    #[test]
    fn a_put_all_carrying_an_oversized_value_writes_nothing() {
        // The atomicity claim, stated as a negative: one bad entry must not
        // leave the good ones behind.
        let l = open_with(LockerConfig::default().with_max_inline(64)).unwrap();
        let entries = vec![
            ("ok".to_string(), "small".to_string()),
            ("bad".to_string(), "x".repeat(10_000)),
        ];

        assert!(matches!(
            block_on(l.put_all(entries)),
            Err(Error::ValueTooLarge { .. })
        ));
        assert_eq!(l.len(), 0, "a refused put_all must write nothing at all");
    }

    #[test]
    fn an_empty_bulk_operation_is_a_no_op() {
        let l = locker();
        block_on(l.put("k", "v".into())).unwrap();
        block_on(l.put_all(Vec::<(String, String)>::new())).unwrap();
        block_on(l.delete_all(Vec::<String>::new())).unwrap();
        assert_eq!(l.len(), 1);
    }

    #[test]
    fn range_and_to_map_read_straight_from_ram() {
        let l = locker();
        for k in ["a", "b", "c", "d"] {
            block_on(l.put(k, k.to_uppercase())).unwrap();
        }

        let keys: Vec<String> = l.range("b".."d").into_iter().map(|(k, _)| k).collect();
        assert_eq!(keys, vec!["b", "c"]);
        assert_eq!(l.range(..).len(), 4);

        let map = l.to_map();
        assert_eq!(map.len(), 4);
        assert_eq!(map.get("c").map(|v| v.as_str()), Some("C"));
    }

    #[test]
    fn watch_keys_passes_any_named_key_and_every_clear() {
        let l = locker();
        let mut events = l.watch_keys(&["a", "b"]);

        block_on(l.put("ignored", "x".into())).unwrap();
        block_on(l.put("b", "y".into())).unwrap();
        block_on(l.clear()).unwrap();

        assert_eq!(
            block_on(events.next()),
            Some(crate::watch::Event::Put { key: b"b".to_vec() })
        );
        assert_eq!(block_on(events.next()), Some(crate::watch::Event::Cleared));
    }

    #[test]
    fn values_are_shared_not_cloned_per_read() {
        let l = locker();
        let stored = block_on(l.put("k", "v".into())).unwrap();
        let read = l.get("k").unwrap();
        assert!(
            Arc::ptr_eq(&stored, &read),
            "reads should hand back the same Arc, not a fresh clone"
        );
    }
}