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
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
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
//! The bank: the root handle, and the registry that maps locker names to ids.
//!
//! # Why a registry
//!
//! Lockers are a key prefix, not a table (see [`crate::backend::api::Table`]),
//! so each one needs a small numeric id. The mapping from name to id lives in
//! the `meta` table and is stable for the life of the data — renaming is not
//! supported, and an id is never reused, so a stale key can never be read as
//! belonging to a different locker.
//!
//! Ids are handed out by a persisted counter rather than a hash of the name.
//! A hash would collide eventually and, worse, silently: two lockers sharing a
//! prefix would interleave their keys.

use std::collections::HashMap;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex, Weak};

use futures::channel::mpsc;

use crate::backend::api::{Backend, Op, ScanRequest, Table};
use crate::backend::KeyRange;
use crate::codec::{default_chain, type_tag, FilterChain};
use crate::error::{Error, Result};

use crate::handle::{Job, JOB_QUEUE};
use crate::key::LockerId;
use crate::locker::eager::EagerValues;
use crate::locker::inner::Inner;
use crate::locker::transaction::TxMode;
use crate::locker::{LazyLocker, Locker, LockerConfig};
use serde::{de::DeserializeOwned, Serialize};

/// On-disk format version for the bank as a whole.
///
/// Distinct from the value envelope's version. This one gates the *layout*
/// (which tables exist, how meta keys are spelled); that one gates how a single
/// value is packed.
pub const FORMAT_VERSION: u32 = 1;

const META_FORMAT_VERSION: &[u8] = b"format_version";
const META_NEXT_LOCKER_ID: &[u8] = b"next_locker_id";
const META_LOCKER_PREFIX: &[u8] = b"locker::";
const META_SCHEMA_PREFIX: &[u8] = b"schema::";
const META_CHAIN_PREFIX: &[u8] = b"chain::";

fn locker_key(name: &str) -> Vec<u8> {
    let mut k = META_LOCKER_PREFIX.to_vec();
    k.extend_from_slice(name.as_bytes());
    k
}

fn schema_key(id: LockerId) -> Vec<u8> {
    let mut k = META_SCHEMA_PREFIX.to_vec();
    k.extend_from_slice(&id.to_be_bytes());
    k
}

fn chain_key(id: LockerId) -> Vec<u8> {
    let mut k = META_CHAIN_PREFIX.to_vec();
    k.extend_from_slice(&id.to_be_bytes());
    k
}

fn u32_from(bytes: &[u8], what: &str) -> Result<u32> {
    <[u8; 4]>::try_from(bytes)
        .map(u32::from_be_bytes)
        .map_err(|_| Error::Corrupt(format!("{what} is not a 4-byte integer")))
}

/// The state every handle on one locker name shares, held weakly.
///
/// Weakly because the bank must not keep a locker alive: the entry exists to
/// let a later `locker(name)` find the open locker, not to own it.
struct OpenLocker {
    inner: Weak<Inner>,
    resident: Weak<crate::locker::resident::Resident>,
    /// An eager locker's resident value map, type-erased: the bank cannot
    /// name `T`, and the type tag is what proves the downcast is sound.
    /// `None` on a lazy locker, which holds no values.
    ///
    /// `Send + Sync` on every target, not only natively where the bank is
    /// `Sync` and this is reachable through it: `Arc::downcast` — the only way
    /// back to the typed map without `unsafe`, which this crate forbids — is
    /// implemented for `Arc<dyn Any + Send + Sync>` and for nothing else. That
    /// is where an eager value type's two bounds come from.
    values: Option<Weak<dyn std::any::Any + Send + Sync>>,
    kind: TxMode,
    /// [`crate::codec::type_tag`] of the value type it was opened as.
    type_tag: String,
    config: LockerConfig,
}

/// [`OpenLocker`] with every part upgraded, or nothing.
struct Shared {
    inner: Arc<Inner>,
    resident: Arc<crate::locker::resident::Resident>,
    values: Option<Arc<dyn std::any::Any + Send + Sync>>,
    kind: TxMode,
    type_tag: String,
    config: LockerConfig,
}

impl OpenLocker {
    /// The live state, or `None` if the last handle has gone or closed.
    fn upgrade(&self) -> Option<Shared> {
        let inner = self.inner.upgrade()?;
        if inner.is_closed() {
            return None;
        }
        let resident = self.resident.upgrade()?;
        let values = match self.values.as_ref() {
            Some(weak) => Some(weak.upgrade()?),
            None => None,
        };
        Some(Shared {
            inner,
            resident,
            values,
            kind: self.kind,
            type_tag: self.type_tag.clone(),
            config: self.config.clone(),
        })
    }
}

fn kind_word(kind: TxMode) -> &'static str {
    match kind {
        TxMode::Eager => "eager",
        TxMode::Lazy => "lazy",
    }
}

/// The first field two configs disagree on, if any.
///
/// Named rather than merely reported so the caller is told which open to
/// change. The order is the order the fields are declared in.
fn config_conflict(open: &LockerConfig, requested: &LockerConfig) -> Option<&'static str> {
    if open.max_inline != requested.max_inline {
        return Some("max_inline");
    }
    if open.eager_budget != requested.eager_budget {
        return Some("eager_budget");
    }
    if open.policy != requested.policy {
        return Some("policy");
    }
    if open.commit != requested.commit {
        return Some("commit");
    }
    if open.durability != requested.durability {
        return Some("durability");
    }
    if open.on_corrupt != requested.on_corrupt {
        return Some("on_corrupt");
    }
    if open.chunk_size != requested.chunk_size {
        return Some("chunk_size");
    }
    if open.chain_id() != requested.chain_id() {
        return Some("filter chain");
    }
    None
}

/// Where a bank stores its data.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum Location {
    /// Nothing is persisted; the data dies with the handle.
    Memory,
    /// A file on disk. Native only.
    Path(std::path::PathBuf),
    /// A named IndexedDB database. Web only.
    Web(String),
}

/// How to open a bank.
///
/// The location is always explicit. crossbank does not guess a platform
/// default, because a library with no knowledge of the calling application has
/// no business choosing where that application's data lives.
///
/// ```no_run
/// use crossbank::BankConfig;
///
/// let on_disk = BankConfig::at("/home/me/.local/share/app/app.crossbank"); // native
/// let in_browser = BankConfig::web("app").with_coherence(true);            // wasm32
/// let nowhere = BankConfig::memory();                                      // tests
/// # let _ = (on_disk, in_browser, nowhere);
/// ```
#[derive(Debug, Clone)]
pub struct BankConfig {
    pub location: Location,

    /// Keep other tabs of this web application in step with this one.
    ///
    /// Off by default. When on, a bank posts what each commit changed on a
    /// `BroadcastChannel` named `crossbank::{database name}`, and applies what
    /// other tabs post to its own resident state — a lazy locker's key index,
    /// an eager locker's values — raising the same [`crate::Event`]s a local
    /// write would.
    ///
    /// **It changes what an eager locker can return.** A value another tab
    /// wrote that is too large to carry in a message cannot be decoded here
    /// without an await, and an eager `get()` cannot await, so the resident
    /// copy is dropped and [`crate::Event::Stale`] is raised. The key is then
    /// gone from *every* resident answer, not just `get()`: `len()`, `keys()`,
    /// `keys_bytes()`, `contains_key()`, `entries()` and `to_map()` all stop
    /// reporting it, until the locker is closed and opened again, which reads
    /// the bytes that are still perfectly intact in storage. (Closed and
    /// opened, not merely opened again: every handle on a name is a view of
    /// one open locker — see [`Bank::locker_with`].) Lazy lockers have no such limit:
    /// their key index is updated either way.
    ///
    /// # How two tabs writing one key are resolved
    ///
    /// **Newest epoch wins, per tab clock.** Each bank keeps a counter it
    /// bumps once per commit that has news, and stamps it on the message. A
    /// receiving eager locker drops a message whose epoch is at or below one
    /// it has already applied, and drops any change whose key this tab itself
    /// committed at an equal or higher epoch of its own.
    ///
    /// That makes two things true, and one thing not:
    ///
    /// * A tab never has its own committed write undone by a message that was
    ///   already in flight when it wrote.
    /// * A message that arrives twice, or out of order behind a newer one, is
    ///   ignored rather than replayed.
    /// * **Two tabs writing the same key concurrently are not ordered.** The
    ///   counters are independent — they are not a vector clock, and there is
    ///   no shared clock to make one from — so which resident copy each tab
    ///   ends up holding depends on message timing. Storage itself is always
    ///   consistent: the backend serialises the commits and the last one to
    ///   land is what is stored. It is only the *resident* copies that may
    ///   disagree with it until a reopen. If two tabs genuinely write one key,
    ///   put it in a lazy locker, which reads through to storage.
    ///
    /// A lazy locker's byte budget is kept in step with another tab's news
    /// too; where a message cannot state a size, the accounting is reloaded
    /// from storage before the next commit plans an eviction.
    ///
    /// Native accepts the flag and does nothing — `redb` takes an exclusive
    /// file lock, so there is no second process to stay coherent with.
    pub coherence: bool,

    /// The filter chain every locker in this bank reads and writes through,
    /// unless a locker names its own with [`LockerConfig::with_chain`].
    ///
    /// `None` means [`crate::codec::default_chain`] — LZ4 then CRC32. Set it
    /// with [`BankConfig::with_chain`].
    pub chain: Option<Arc<FilterChain>>,
}

impl BankConfig {
    pub fn memory() -> Self {
        Self {
            location: Location::Memory,
            coherence: false,
            chain: None,
        }
    }

    pub fn at(path: impl Into<std::path::PathBuf>) -> Self {
        Self {
            location: Location::Path(path.into()),
            coherence: false,
            chain: None,
        }
    }

    pub fn web(name: impl Into<String>) -> Self {
        Self {
            location: Location::Web(name.into()),
            coherence: false,
            chain: None,
        }
    }

    /// See [`BankConfig::coherence`]. Never on by default.
    pub fn with_coherence(mut self, on: bool) -> Self {
        self.coherence = on;
        self
    }

    /// Open the bank under a specific filter chain.
    ///
    /// [`Bank::with_backend_and_chain`] can already do this over a backend you
    /// built yourself; this is the same choice from a *location*, so a
    /// consumer opening a real file or a real IndexedDB database does not have
    /// to reach past [`Bank::open`] to make it.
    ///
    /// The chain id is persisted per locker and enforced on every later open
    /// (see [`Bank::bind_schema`]'s neighbour, `bind_chain`), so this is a
    /// decision about a *store*, not a runtime option: reopening the same bank
    /// under a different chain is [`Error::SchemaMismatch`], not a re-encode.
    ///
    /// ```no_run
    /// use std::sync::Arc;
    /// use crossbank::{Bank, BankConfig, FilterChain};
    ///
    /// # async fn demo() -> crossbank::Result<()> {
    /// // Checksums, no compression — for payloads LZ4 cannot shrink.
    /// let bank = Bank::open(
    ///     BankConfig::at("candles.crossbank").with_chain(Arc::new(FilterChain::checksum_only())),
    /// )
    /// .await?;
    /// assert_eq!(bank.chain().describe(), "chain 2 (crc32)");
    /// # Ok(())
    /// # }
    /// ```
    pub fn with_chain(mut self, chain: Arc<FilterChain>) -> Self {
        self.chain = Some(chain);
        self
    }
}

/// The root handle. Lockers are opened from it. Hive's `Hive` static, made a
/// value you own.
///
/// One bank is one store — a `redb` file natively, one IndexedDB database on
/// the web — and every locker inside it shares that store, its filter chain
/// and its chunk-id allocator. Opening the same locker name twice is allowed
/// and every handle on a name is a view of the **one** open locker, exactly as
/// `Hive.box(name)` is — see [`Bank::locker_with`].
///
/// ```no_run
/// use crossbank::{Bank, BankConfig, LazyLocker, Locker};
///
/// # async fn demo() -> crossbank::Result<()> {
/// // Native. On the web this is `BankConfig::web("app")`, and
/// // `BankConfig::memory()` stores nothing anywhere.
/// let bank = Bank::open(BankConfig::at("app.crossbank")).await?;
///
/// let settings: Locker<String> = bank.locker("settings").await?;
/// let candles: LazyLocker<Vec<f64>> = bank.lazy_locker("candles").await?;
///
/// // Hive's `isBoxOpen` / `boxExists`: one asks about this process, the
/// // other about the store.
/// assert!(bank.is_locker_open("settings"));
/// assert!(bank.locker_exists("candles").await?);
///
/// // On the web, ask the browser to keep the data — and handle "no".
/// // Never on a startup path: Firefox prompts the user and this does not
/// // resolve until they answer.
/// let _kept = bank.persist().await?;
/// if let Some(usage) = bank.usage().await? {
///     println!("{usage:?}");
/// }
///
/// // One call covers every open locker's staged writes and its fsync.
/// bank.flush_all().await?;
/// bank.close().await?;
/// # Ok(())
/// # }
/// ```
pub struct Bank {
    backend: Arc<dyn Backend>,
    chain: Arc<FilterChain>,
    /// Name to id, cached so opening a locker twice does not re-read `meta`.
    registry: Mutex<HashMap<String, LockerId>>,
    /// Every per-locker filter chain this bank knows, by chain id.
    ///
    /// Bank-level maintenance — [`Bank::verify`], [`Bank::quarantine`],
    /// [`Bank::locker_bytes`] — reads records without a locker handle, so it
    /// has no config to take a chain from. It resolves the chain from the
    /// `chain::{id}` meta record and looks the id up here. Filled
    /// automatically whenever a locker is opened with its own chain, and
    /// fillable ahead of time with [`Bank::register_chain`] for maintenance
    /// that runs before any such open.
    chains: Mutex<HashMap<u8, Arc<FilterChain>>>,
    /// Cloned into every [`crate::BankHandle`].
    job_sender: mpsc::Sender<Job>,
    /// Taken exactly once, by `into_service`. A second service would silently
    /// steal jobs from the first.
    job_receiver: Mutex<Option<mpsc::Receiver<Job>>>,
    /// Name to the one open locker under it.
    ///
    /// **One entry per name, and every handle on that name is a view of it.**
    /// Handing out independent handles instead let one handle serve a read
    /// from RAM that another handle had already overwritten — silently, and
    /// with no error anywhere. See [`Bank::locker`].
    ///
    /// `Weak` throughout, so a locker the application dropped stops counting
    /// as open without needing a destructor to reach back into the bank.
    /// Entries are pruned lazily on every read, and the entry outlives any
    /// one handle: it goes when the last one does.
    open_lockers: Mutex<HashMap<String, OpenLocker>>,
    /// The staged-write buffers of every open locker.
    ///
    /// `Weak`, and non-generic, so [`Bank::flush_all`] can commit them all
    /// without knowing any locker's value type and without keeping a dropped
    /// locker alive.
    residents: Mutex<Vec<Weak<crate::locker::resident::Resident>>>,
    /// Bank-wide facilities (chunk value ids, LRU ticks, coherence), cloned into every
    /// locker so two handles on one name cannot collide.
    shared: Arc<crate::locker::inner::Shared>,
    closed: AtomicBool,
    /// This bank's entry in [`OPEN_BANKS`], while it holds one.
    ///
    /// Only a bank opened from a [`Location::Path`] has one. It is taken by
    /// whichever of [`Bank::close`] and `Drop` runs first, so a later reopen
    /// of the same file cannot have its entry removed by the previous bank
    /// finally being dropped.
    #[cfg(not(target_arch = "wasm32"))]
    tracked_path: Mutex<Option<std::path::PathBuf>>,
}

/// Frees the bank's name in [`OPEN_BANKS`] for a bank that was dropped without
/// being closed. Bookkeeping only — it awaits nothing and touches no storage,
/// because a destructor cannot await and a closing process would not run one
/// anyway.
#[cfg(not(target_arch = "wasm32"))]
impl Drop for Bank {
    fn drop(&mut self) {
        self.release_tracked_path();
    }
}

impl std::fmt::Debug for Bank {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Bank").field("chain", &self.chain).finish()
    }
}

impl Bank {
    /// Ask the platform to keep this bank's data.
    ///
    /// On wasm this is `navigator.storage.persist()`. On native the file is
    /// already durable, so this returns `Ok(true)`. Never called implicitly
    /// on open — precious data on the web must opt in.
    ///
    /// Browsers differ: Chromium decides silently from site-engagement
    /// heuristics, while Firefox shows the user a permission prompt and the
    /// returned future does not resolve until they answer it. Call this off
    /// the startup path and never block a UI on it.
    pub async fn persist(&self) -> Result<bool> {
        #[cfg(not(target_arch = "wasm32"))]
        {
            let _ = self;
            Ok(true)
        }
        #[cfg(target_arch = "wasm32")]
        {
            let _ = self;
            let Some(window) = web_sys::window() else {
                return Ok(false);
            };
            match window.navigator().storage().persist() {
                Ok(promise) => {
                    let value = wasm_bindgen_futures::JsFuture::from(promise)
                        .await
                        .map_err(|e| Error::backend(format!("{e:?}")))?;
                    Ok(value.as_bool().unwrap_or(false))
                }
                Err(_) => Ok(false),
            }
        }
    }

    /// What the platform says this bank's storage is costing.
    ///
    /// `None` where the platform does not report it. Reporting a fabricated
    /// number would be worse than reporting nothing.
    ///
    /// The figure is **not** comparable across backends, and that is
    /// deliberate rather than an oversight:
    ///
    /// * On the web it is `navigator.storage.estimate()`, which is
    ///   **origin-wide** — every IndexedDB database, Cache Storage entry and
    ///   service worker on the origin, not just this bank. It is also
    ///   deliberately coarsened by browsers to frustrate fingerprinting.
    /// * On `redb` it is the size of the bank file, which includes free pages
    ///   the database has not returned to the filesystem.
    /// * In memory it is the sum of the key and value lengths held.
    ///
    /// For a number crossbank actually owns and can attribute to one locker,
    /// use [`Bank::locker_bytes`] or
    /// [`crate::LazyLocker::budget_used`].
    pub async fn usage(&self) -> Result<Option<crate::backend::Usage>> {
        self.ensure_open()?;
        self.backend.usage().await
    }

    /// Whether the platform has granted this origin persistent storage.
    ///
    /// Always `true` natively — nothing evicts a file behind the
    /// application's back. On the web this is `navigator.storage.persisted()`,
    /// a **read**: unlike [`Bank::persist`] it never prompts and never
    /// changes anything, so it is safe on a startup path.
    ///
    /// `false` on the web is not a fault. It means the browser may reclaim
    /// this origin's storage under pressure — and, on Safari, after seven days
    /// without user interaction regardless of pressure. See the "Web caveats"
    /// section of the README.
    pub async fn is_persisted(&self) -> Result<bool> {
        #[cfg(not(target_arch = "wasm32"))]
        {
            self.ensure_open()?;
            Ok(true)
        }
        #[cfg(target_arch = "wasm32")]
        {
            self.ensure_open()?;
            let Some(window) = web_sys::window() else {
                return Ok(false);
            };
            match window.navigator().storage().persisted() {
                Ok(promise) => {
                    let value = wasm_bindgen_futures::JsFuture::from(promise)
                        .await
                        .map_err(|e| Error::backend(format!("{e:?}")))?;
                    Ok(value.as_bool().unwrap_or(false))
                }
                Err(_) => Ok(false),
            }
        }
    }

    /// Refuse an operation on a closed bank.
    fn ensure_open(&self) -> Result<()> {
        if self.is_closed() {
            return Err(Error::Closed);
        }
        Ok(())
    }

    /// Open a bank at the location named in `config`.
    ///
    /// The location is always explicit. `Location::Path` is native-only;
    /// `Location::Web` is wasm-only. The other combination is
    /// [`Error::InvalidConfig`].
    pub async fn open(config: BankConfig) -> Result<Self> {
        // Coherence is a web facility: it needs a channel name, and the name
        // is the database name. Nothing else has one.
        let coherence = match (&config.location, config.coherence) {
            (Location::Web(name), true) => crate::coherence::Coherence::open(name),
            _ => crate::coherence::Coherence::disabled(),
        };
        let chain = config
            .chain
            .clone()
            .unwrap_or_else(|| Arc::new(default_chain()));
        match config.location {
            Location::Memory => {
                Self::assembled(
                    Arc::new(crate::backend::MemoryBackend::new()),
                    chain,
                    coherence,
                )
                .await
            }
            Location::Path(path) => {
                #[cfg(not(target_arch = "wasm32"))]
                {
                    // Registered only once the backend is really open, and
                    // keyed off the file as it exists then, so the key matches
                    // the one `delete_bank` computes for the same location.
                    let located = path.clone();
                    let bank = Self::assembled(
                        Arc::new(crate::backend::RedbBackend::open(path)?),
                        chain,
                        coherence,
                    )
                    .await?;
                    let key = bank_key(&located);
                    register_open_bank(key.clone());
                    if let Ok(mut guard) = bank.tracked_path.lock() {
                        *guard = Some(key);
                    }
                    Ok(bank)
                }
                #[cfg(target_arch = "wasm32")]
                {
                    let _ = path;
                    Err(Error::InvalidConfig(
                        "Location::Path is native-only; use Location::Web on wasm".into(),
                    ))
                }
            }
            Location::Web(name) => {
                #[cfg(target_arch = "wasm32")]
                {
                    let backend = crate::backend::IndexedDbBackend::open(&name).await?;
                    Self::assembled(Arc::new(backend), chain, coherence).await
                }
                #[cfg(not(target_arch = "wasm32"))]
                {
                    let _ = name;
                    Err(Error::InvalidConfig(
                        "Location::Web is wasm-only; use Location::Path on native".into(),
                    ))
                }
            }
        }
    }

    /// Open a bank over an already-constructed backend.
    ///
    /// **One `Bank` per backend instance.** Two banks over one backend are not
    /// two views of a store, they are two uncoordinated writers: each keeps
    /// its own open-locker registry, so neither can see that the other holds a
    /// handle on a name — so the sharing that makes two handles on one name
    /// one locker stops at the bank boundary, and the two banks' RAM indexes
    /// and resident values silently diverge. That is the `name_shared` hazard
    /// (see `PLAN.md`, "Known limitations"), and it also defeats
    /// `delete_locker`'s and `quarantine`'s "is it open?" refusals and
    /// `flush_all`'s claim to cover every open locker.
    ///
    /// Share the one `Bank` (it is `Sync`, and [`crate::BankHandle`] is
    /// cheap), rather than reopening over the same backend `Arc`. Separate
    /// processes or tabs are a different question, and are what
    /// [`crate::coherence`] is for.
    pub async fn with_backend(backend: Arc<dyn Backend>) -> Result<Self> {
        Self::with_backend_and_chain(backend, default_chain()).await
    }

    /// As [`Bank::with_backend`], with a specific filter chain.
    pub async fn with_backend_and_chain(
        backend: Arc<dyn Backend>,
        chain: FilterChain,
    ) -> Result<Self> {
        Self::assembled(
            backend,
            Arc::new(chain),
            crate::coherence::Coherence::disabled(),
        )
        .await
    }

    async fn assembled(
        backend: Arc<dyn Backend>,
        chain: Arc<FilterChain>,
        coherence: crate::coherence::Coherence,
    ) -> Result<Self> {
        let shared = Arc::new(crate::locker::inner::Shared {
            coherence,
            ..Default::default()
        });
        let (job_sender, job_receiver) = mpsc::channel(JOB_QUEUE);
        let bank = Self {
            backend,
            chain,
            registry: Mutex::new(HashMap::new()),
            chains: Mutex::new(HashMap::new()),
            job_sender,
            job_receiver: Mutex::new(Some(job_receiver)),
            open_lockers: Mutex::new(HashMap::new()),
            residents: Mutex::new(Vec::new()),
            shared: shared.clone(),
            closed: AtomicBool::new(false),
            #[cfg(not(target_arch = "wasm32"))]
            tracked_path: Mutex::new(None),
        };
        bank.check_or_write_format_version().await?;
        Ok(bank)
    }

    pub fn backend(&self) -> &Arc<dyn Backend> {
        &self.backend
    }

    pub fn chain(&self) -> &Arc<FilterChain> {
        &self.chain
    }

    /// Refuse to touch a store written by a future, incompatible layout.
    async fn check_or_write_format_version(&self) -> Result<()> {
        match self.backend.get(Table::Meta, META_FORMAT_VERSION).await? {
            Some(raw) => {
                let found = u32_from(&raw, "format version")?;
                if found != FORMAT_VERSION {
                    return Err(Error::UnsupportedVersion {
                        // Saturating because the layout version is u32 while the
                        // error reports a u8; a mismatch is fatal either way and
                        // the exact number only has to be legible.
                        found: found.min(u8::MAX as u32) as u8,
                        supported: FORMAT_VERSION as u8,
                    });
                }
                Ok(())
            }
            None => {
                self.backend
                    .commit(vec![Op::Put {
                        table: Table::Meta,
                        key: META_FORMAT_VERSION.to_vec(),
                        value: FORMAT_VERSION.to_be_bytes().to_vec(),
                    }])
                    .await
            }
        }
    }

    /// The id for `name`, allocating one on first use.
    pub async fn locker_id(&self, name: &str) -> Result<LockerId> {
        if let Some(id) = self.cached(name) {
            return Ok(id);
        }

        // One round trip, not two. The registration and the id counter are
        // both `meta` keys, so a single `get_many` answers "is this name
        // known?" and "what is the next free id?" together — and on IndexedDB
        // each of those gets would otherwise be its own transaction.
        let mut found = self
            .backend
            .get_many(
                Table::Meta,
                vec![locker_key(name), META_NEXT_LOCKER_ID.to_vec()],
            )
            .await?;
        let next_raw = found.pop().flatten();
        let registered = found.pop().flatten();

        if let Some(raw) = registered {
            let id = u32_from(&raw, "locker id")?;
            self.cache(name, id);
            return Ok(id);
        }

        let next = match next_raw {
            Some(raw) => u32_from(&raw, "next locker id")?,
            None => 0,
        };
        let id = next;
        let bumped = next
            .checked_add(1)
            .ok_or_else(|| Error::backend("locker id space is exhausted"))?;

        // Registration and the counter bump land together, so a failure cannot
        // leave a name pointing at an id the counter will hand out again.
        self.backend
            .commit(vec![
                Op::Put {
                    table: Table::Meta,
                    key: locker_key(name),
                    value: id.to_be_bytes().to_vec(),
                },
                Op::Put {
                    table: Table::Meta,
                    key: META_NEXT_LOCKER_ID.to_vec(),
                    value: bumped.to_be_bytes().to_vec(),
                },
            ])
            .await?;

        self.cache(name, id);
        Ok(id)
    }

    /// Open an eager locker: values resident, reads synchronous.
    ///
    /// For settings-shaped data — small, hot, read from paths that cannot
    /// await. Fails if the stored contents exceed the configured budget, which
    /// is the guardrail against reaching for this where a lazy locker was
    /// meant.
    ///
    /// **Opening a name that is already open returns another handle onto the
    /// same open locker**, exactly as Hive's `Hive.box(name)` does — see
    /// [`Bank::locker_with`].
    pub async fn locker<T>(&self, name: &str) -> Result<Locker<T>>
    where
        // `'static` because an eager locker's resident values are what a
        // coherence callback replaces, and a callback outlives the call that
        // installed it. `Send + Sync` because every handle on a name shares
        // one resident map, the bank holds it type-erased to do that, and
        // `Arc::downcast` — the only `unsafe`-free way back to the typed map —
        // exists solely for `Arc<dyn Any + Send + Sync>`. Both hold for any
        // ordinary serialisable value type.
        T: Serialize + DeserializeOwned + Send + Sync + 'static,
    {
        self.locker_with(name, LockerConfig::default()).await
    }

    /// As [`Bank::locker`], with explicit limits.
    ///
    /// # Opening one name twice
    ///
    /// Allowed, and the second handle is a **view of the first**: one resident
    /// map, one staged batch, one set of watchers, shared by every handle on
    /// the name. A `put` through one is visible to a `get` through the other
    /// immediately, and a `watch` on either sees both. That is `Hive.box`'s
    /// contract, and the only one a caller can hold safely — two independent
    /// handles served stale reads from their own RAM with no error anywhere.
    ///
    /// Because they share, the two opens must agree:
    ///
    /// * a different value type, or opening a lazy name eagerly (or the other
    ///   way round), is [`Error::SchemaMismatch`];
    /// * a different [`LockerConfig`] is [`Error::InvalidConfig`], naming the
    ///   field that differs.
    ///
    /// A shared open reads nothing from storage — the first open already did.
    /// [`Locker::close`] closes the locker for **every** handle on the name,
    /// as `box.close()` does in Hive; opening the name again afterwards opens
    /// it afresh.
    pub async fn locker_with<T>(&self, name: &str, config: LockerConfig) -> Result<Locker<T>>
    where
        T: Serialize + DeserializeOwned + Send + Sync + 'static,
    {
        self.ensure_open()?;
        let chain = self.chain_for(&config);
        if let Some(open) = self.open_locker(name) {
            return Self::share_eager(name, open, &config);
        }

        let id = self.prepare::<T>(name, &chain).await?;
        let locker = Locker::open(
            self.backend.clone(),
            chain,
            id,
            name.to_string(),
            config.clone(),
            self.shared.clone(),
        )
        .await?;
        // The registry check above is not a claim: `prepare` and `open` both
        // await, and a second open of this name can pass the same check and
        // finish first. Claiming the name under the lock — and sharing the
        // winner when someone else holds it — is what makes one name one
        // locker even then. See trap 39.
        let claim = OpenLocker {
            inner: Arc::downgrade(locker.inner()),
            resident: Arc::downgrade(locker.resident()),
            values: Some(
                Arc::downgrade(locker.shared_values()) as Weak<dyn std::any::Any + Send + Sync>
            ),
            kind: TxMode::Eager,
            type_tag: type_tag::<T>(),
            config: config.clone(),
        };
        if let Some(open) = self.claim_open(name, claim) {
            return Self::share_eager(name, open, &config);
        }
        self.register_resident(locker.resident());
        locker.join_coherence();
        Ok(locker)
    }

    /// Another handle onto the open eager locker `name`, if it agrees.
    fn share_eager<T>(name: &str, open: Shared, config: &LockerConfig) -> Result<Locker<T>>
    where
        T: Serialize + DeserializeOwned + Send + Sync + 'static,
    {
        Self::check_shared::<T>(name, &open, TxMode::Eager, config)?;
        let values = open
            .values
            .clone()
            .and_then(|erased| erased.downcast::<EagerValues<T>>().ok())
            .ok_or_else(|| Error::SchemaMismatch {
                stored: open.type_tag.clone(),
                requested: type_tag::<T>(),
            })?;
        Ok(Locker::from_shared(open.inner, values, open.resident))
    }

    /// Open a lazy locker: key index resident, values fetched on demand.
    ///
    /// For bulk data. Open cost scales with the number of keys, not the size
    /// of the data.
    ///
    /// **Opening a name that is already open returns another handle onto the
    /// same open locker** — see [`Bank::locker_with`], whose rules apply here
    /// unchanged.
    pub async fn lazy_locker<T>(&self, name: &str) -> Result<LazyLocker<T>>
    where
        T: Serialize + DeserializeOwned,
    {
        self.lazy_locker_with(name, LockerConfig::default()).await
    }

    /// As [`Bank::lazy_locker`], with explicit limits.
    ///
    /// Opening one name twice shares the key index, the byte budget, the
    /// staged batch and the watchers, under the same agreement rules as
    /// [`Bank::locker_with`].
    pub async fn lazy_locker_with<T>(
        &self,
        name: &str,
        config: LockerConfig,
    ) -> Result<LazyLocker<T>>
    where
        T: Serialize + DeserializeOwned,
    {
        self.ensure_open()?;
        let chain = self.chain_for(&config);
        if let Some(open) = self.open_locker(name) {
            return Self::share_lazy(name, open, &config);
        }

        let id = self.prepare::<T>(name, &chain).await?;
        let locker = LazyLocker::open(
            self.backend.clone(),
            chain,
            id,
            name.to_string(),
            config.clone(),
            self.shared.clone(),
        )
        .await?;
        // See `locker_with`: the check before the awaits is not a claim.
        let claim = OpenLocker {
            inner: Arc::downgrade(locker.inner()),
            resident: Arc::downgrade(locker.resident()),
            values: None,
            kind: TxMode::Lazy,
            type_tag: type_tag::<T>(),
            config: config.clone(),
        };
        if let Some(open) = self.claim_open(name, claim) {
            return Self::share_lazy(name, open, &config);
        }
        self.register_resident(locker.resident());
        locker.join_coherence();
        Ok(locker)
    }

    /// Another handle onto the open lazy locker `name`, if it agrees.
    fn share_lazy<T>(name: &str, open: Shared, config: &LockerConfig) -> Result<LazyLocker<T>>
    where
        T: Serialize + DeserializeOwned,
    {
        Self::check_shared::<T>(name, &open, TxMode::Lazy, config)?;
        Ok(LazyLocker::from_shared(open.inner, open.resident))
    }

    /// The chain a locker opened with `config` reads and writes through.
    fn chain_for(&self, config: &LockerConfig) -> Arc<FilterChain> {
        match config.chain.clone() {
            Some(chain) => {
                self.register_chain(chain.clone());
                chain
            }
            None => self.chain.clone(),
        }
    }

    /// Teach the bank a filter chain so maintenance can find it by id.
    ///
    /// [`Bank::verify`], [`Bank::quarantine`], [`Bank::locker_bytes`] and
    /// [`Bank::delete_locker`] read records with no locker handle and so no
    /// config: they resolve each locker's chain from its `chain::{id}` meta
    /// record and look the id up in this registry. Opening a locker with
    /// [`LockerConfig::with_chain`] registers it for you, so this is only
    /// needed to verify a locker that has not been opened in this process.
    ///
    /// Last registration of an id wins. The bank chain is always known and
    /// never needs registering.
    pub fn register_chain(&self, chain: Arc<FilterChain>) {
        if let Ok(mut guard) = self.chains.lock() {
            guard.insert(chain.id(), chain);
        }
    }

    /// The chain id a locker's records were sealed with, if one was recorded.
    ///
    /// `None` means the store predates the `chain::` record, which is
    /// "written under whatever the bank chain was" — see [`Bank::bind_chain`].
    async fn stored_chain_id(&self, id: LockerId) -> Result<Option<u8>> {
        match self.backend.get(Table::Meta, &chain_key(id)).await? {
            Some(raw) => {
                let [stored] = raw[..] else {
                    return Err(Error::Corrupt(
                        "a locker's filter chain id is not a single byte".into(),
                    ));
                };
                Ok(Some(stored))
            }
            None => Ok(None),
        }
    }

    /// Resolve the chain one locker's records are sealed with.
    ///
    /// `Ok(None)` is "this locker names a chain id nothing in this process
    /// knows". That is not corruption — it is a locker written by a build, or
    /// a caller, that had a chain this one has not been told about. Reading
    /// its payloads is impossible; deleting them is still perfectly possible,
    /// which is why the callers that only move bytes around fall back to the
    /// bank chain and only [`Bank::verify`] refuses.
    async fn locker_chain(&self, id: LockerId) -> Result<Option<Arc<FilterChain>>> {
        let Some(stored) = self.stored_chain_id(id).await? else {
            return Ok(Some(self.chain.clone()));
        };
        if stored == self.chain.id() {
            return Ok(Some(self.chain.clone()));
        }
        Ok(self
            .chains
            .lock()
            .ok()
            .and_then(|guard| guard.get(&stored).cloned()))
    }

    /// As [`Bank::locker_chain`], falling back to the bank chain for an
    /// unknown id. For maintenance that never opens a payload.
    async fn locker_chain_or_bank(&self, id: LockerId) -> Result<Arc<FilterChain>> {
        Ok(self
            .locker_chain(id)
            .await?
            .unwrap_or_else(|| self.chain.clone()))
    }

    /// Resolve the id and bind both the value type and the filter chain, so
    /// reopening a locker under a different `T` — or a different chain — is
    /// caught rather than silently mis-decoded.
    async fn prepare<T>(&self, name: &str, chain: &FilterChain) -> Result<LockerId> {
        // Asked *before* `locker_id`, which registers the name as a side
        // effect: "did this locker already have data?" is the question
        // `bind_chain` needs, and a moment later the answer is always yes.
        let pre_existing = self.locker_exists(name).await?;
        let id = self.locker_id(name).await?;
        self.bind_schema(id, &type_tag::<T>()).await?;
        self.bind_chain(id, chain, pre_existing).await?;
        Ok(id)
    }

    /// Record, or verify, the filter chain a locker is stored under.
    ///
    /// The same first-write-wins rule as [`Bank::bind_schema`], and for the
    /// same reason: a chain id names how bytes were transformed, so opening a
    /// locker under a different one would hand stored values to the wrong
    /// inverse transform and decode them into plausible garbage.
    ///
    /// A locker written before this record existed simply has none. That is
    /// not a mismatch — it was written with whatever the bank chain was, which
    /// is what an open with no per-locker chain still uses — so the id is
    /// written on this open and enforced from the next one.
    ///
    /// `pre_existing` is what makes that safe. A missing record on a name that
    /// *already held data* means exactly one thing: the data was sealed with
    /// the bank chain by a build that had no per-locker chains. Adopting the
    /// requested chain there would stamp a lie into `meta` and brick the
    /// locker — every stored value read through the wrong inverse transform,
    /// for good. So a pre-existing name persists the **bank** chain id, and an
    /// open that asked for anything else is refused. Only a genuinely fresh
    /// name adopts the chain it was opened with.
    async fn bind_chain(
        &self,
        id: LockerId,
        chain: &FilterChain,
        pre_existing: bool,
    ) -> Result<()> {
        let key = chain_key(id);
        match self.backend.get(Table::Meta, &key).await? {
            Some(raw) => {
                let [stored] = raw[..] else {
                    return Err(Error::Corrupt(
                        "a locker's filter chain id is not a single byte".into(),
                    ));
                };
                if stored != chain.id() {
                    return Err(Error::SchemaMismatch {
                        stored: format!(
                            "filter chain {stored}; this locker's values were sealed with it"
                        ),
                        requested: format!(
                            "{} — reopen the locker with the chain it was written under, \
                             or use a new locker name",
                            chain.describe()
                        ),
                    });
                }
                Ok(())
            }
            None => {
                let adopted = if pre_existing {
                    if chain.id() != self.chain.id() {
                        return Err(Error::SchemaMismatch {
                            stored: format!(
                                "no filter chain record; this locker predates per-locker \
                                 chains, so its values were sealed with the bank chain \
                                 ({})",
                                self.chain.describe()
                            ),
                            requested: format!(
                                "{} — reopen it under the bank chain, which records the \
                                 chain id from then on, or copy its values into a new \
                                 locker name",
                                chain.describe()
                            ),
                        });
                    }
                    self.chain.id()
                } else {
                    chain.id()
                };
                self.backend
                    .commit(vec![Op::Put {
                        table: Table::Meta,
                        key,
                        value: vec![adopted],
                    }])
                    .await
            }
        }
    }

    pub(crate) fn job_sender(&self) -> mpsc::Sender<Job> {
        self.job_sender.clone()
    }

    pub(crate) fn take_job_receiver(&self) -> Option<mpsc::Receiver<Job>> {
        self.job_receiver.lock().ok()?.take()
    }

    /// Bytes-level access, used by [`crate::BankHandle`].
    ///
    /// Values go through the same envelope and filter chain as typed ones, and
    /// bind the same schema tag, so a locker reached this way is precisely a
    /// `Locker<Vec<u8>>` — the two views cannot disagree.
    /// Always the **bank** chain: a handle carries no config, so a locker
    /// given its own chain is refused here rather than read through the wrong
    /// one.
    async fn raw_locker(&self, name: &str) -> Result<LockerId> {
        let chain = self.chain.clone();
        self.prepare::<Vec<u8>>(name, &chain).await
    }

    pub(crate) async fn raw_get(&self, locker: &str, key: &str) -> Result<Option<Vec<u8>>> {
        let id = self.raw_locker(locker).await?;
        let encoded = crate::key::encode(id, key);
        match self.backend.get(Table::Records, &encoded).await? {
            Some(stored) => Ok(Some(crate::codec::decode(&stored, &self.chain)?)),
            None => Ok(None),
        }
    }

    pub(crate) async fn raw_put(&self, locker: &str, key: &str, value: Vec<u8>) -> Result<()> {
        let id = self.raw_locker(locker).await?;
        let sealed = crate::codec::encode(&value, &self.chain)?;
        self.backend
            .commit(vec![Op::Put {
                table: Table::Records,
                key: crate::key::encode(id, key),
                value: sealed,
            }])
            .await
    }

    pub(crate) async fn raw_delete(&self, locker: &str, key: &str) -> Result<()> {
        let id = self.raw_locker(locker).await?;
        self.backend
            .commit(vec![Op::Delete {
                table: Table::Records,
                key: crate::key::encode(id, key),
            }])
            .await
    }

    pub(crate) async fn raw_clear(&self, locker: &str) -> Result<()> {
        let id = self.raw_locker(locker).await?;
        self.backend
            .commit(vec![Op::DeleteRange {
                table: Table::Records,
                range: crate::key::locker_range(id),
            }])
            .await
    }

    pub(crate) async fn raw_keys(&self, locker: &str, prefix: &str) -> Result<Vec<String>> {
        let id = self.raw_locker(locker).await?;
        let mut range = crate::key::prefix_range(id, prefix);
        let mut keys = Vec::new();

        loop {
            let page = self
                .backend
                .scan(ScanRequest {
                    table: Table::Records,
                    range: range.clone(),
                    reverse: false,
                    limit: 256,
                    want_values: false,
                })
                .await?;

            for (encoded, _) in &page.items {
                keys.push(crate::key::decode(id, encoded)?.to_string());
            }

            match page.resume {
                Some(last) => range.start = std::ops::Bound::Excluded(last),
                None => break,
            }
        }

        Ok(keys)
    }

    /// Read many keys in **one** backend round trip.
    ///
    /// The answers come back positionally: slot `i` is the value for `keys[i]`,
    /// and `None` there means that key is absent. On IndexedDB this is the
    /// difference between one transaction and N of them.
    pub(crate) async fn raw_get_many(
        &self,
        locker: &str,
        keys: Vec<String>,
    ) -> Result<Vec<Option<Vec<u8>>>> {
        if keys.is_empty() {
            return Ok(Vec::new());
        }
        let id = self.raw_locker(locker).await?;
        let encoded: Vec<Vec<u8>> = keys.iter().map(|k| crate::key::encode(id, k)).collect();
        let stored = self.backend.get_many(Table::Records, encoded).await?;

        stored
            .into_iter()
            .map(|slot| match slot {
                Some(bytes) => Ok(Some(crate::codec::decode(&bytes, &self.chain)?)),
                None => Ok(None),
            })
            .collect()
    }

    /// Write many entries in **one** atomic commit.
    ///
    /// Everything lands together or nothing does — one fsync natively, one
    /// IndexedDB transaction on the web. An empty list is `Ok(())` and never
    /// reaches the backend at all.
    pub(crate) async fn raw_put_all(
        &self,
        locker: &str,
        entries: Vec<(String, Vec<u8>)>,
    ) -> Result<()> {
        if entries.is_empty() {
            return Ok(());
        }
        let id = self.raw_locker(locker).await?;
        let mut ops = Vec::with_capacity(entries.len());
        for (key, value) in entries {
            ops.push(Op::Put {
                table: Table::Records,
                key: crate::key::encode(id, &key),
                value: crate::codec::encode(&value, &self.chain)?,
            });
        }
        self.backend.commit(ops).await
    }

    /// Remove many keys in **one** atomic commit. Removing an absent key is
    /// not an error, and an empty list never reaches the backend.
    pub(crate) async fn raw_delete_all(&self, locker: &str, keys: Vec<String>) -> Result<()> {
        if keys.is_empty() {
            return Ok(());
        }
        let id = self.raw_locker(locker).await?;
        let ops = keys
            .into_iter()
            .map(|key| Op::Delete {
                table: Table::Records,
                key: crate::key::encode(id, &key),
            })
            .collect();
        self.backend.commit(ops).await
    }

    /// Every key/value pair under `prefix`, in byte order.
    ///
    /// The same paging loop as [`Bank::raw_keys`], asking the backend for
    /// values as well as keys. The page size comes from the backend rather
    /// than a constant, so a backend that pages cheaply is not held to a
    /// browser-shaped number.
    pub(crate) async fn raw_entries(
        &self,
        locker: &str,
        prefix: &str,
    ) -> Result<Vec<(String, Vec<u8>)>> {
        let id = self.raw_locker(locker).await?;
        let mut range = crate::key::prefix_range(id, prefix);
        let mut entries = Vec::new();
        let limit = self.backend.scan_page_size();

        loop {
            let page = self
                .backend
                .scan(ScanRequest {
                    table: Table::Records,
                    range: range.clone(),
                    reverse: false,
                    limit,
                    want_values: true,
                })
                .await?;

            for (encoded, value) in &page.items {
                let key = crate::key::decode(id, encoded)?.to_string();
                // A scan asked for values and given a key without one is a
                // backend that did not honour `want_values`. Say so, rather
                // than quietly dropping the key from the answer — a listing
                // that is silently short is the worst of the three outcomes.
                let stored = value.as_deref().ok_or_else(|| {
                    Error::Corrupt(format!(
                        "the backend returned no value for {key:?} in a scan that asked for values"
                    ))
                })?;
                entries.push((key, crate::codec::decode(stored, &self.chain)?));
            }

            match page.resume {
                Some(last) => range.start = std::ops::Bound::Excluded(last),
                None => break,
            }
        }

        Ok(entries)
    }

    /// Whether one key is stored, without decoding its value.
    pub(crate) async fn raw_contains_key(&self, locker: &str, key: &str) -> Result<bool> {
        let id = self.raw_locker(locker).await?;
        let encoded = crate::key::encode(id, key);
        Ok(self.backend.get(Table::Records, &encoded).await?.is_some())
    }

    /// How many records one locker holds.
    ///
    /// A key-only scan: the bytes-only view keeps no RAM index, so this is a
    /// count over storage rather than a number already known.
    pub(crate) async fn raw_len(&self, locker: &str) -> Result<usize> {
        let id = self.raw_locker(locker).await?;
        let mut range = crate::key::locker_range(id);
        let mut total = 0usize;
        let limit = self.backend.scan_page_size();

        loop {
            let page = self
                .backend
                .scan(ScanRequest {
                    table: Table::Records,
                    range: range.clone(),
                    reverse: false,
                    limit,
                    want_values: false,
                })
                .await?;

            total += page.items.len();

            match page.resume {
                Some(last) => range.start = std::ops::Bound::Excluded(last),
                None => break,
            }
        }

        Ok(total)
    }

    /// Record, or verify, the schema tag a locker was written with.
    ///
    /// postcard is not self-describing, so without this an application that
    /// changes a locker's value type silently decodes old bytes into the new
    /// shape. First write wins; every later open must match.
    pub async fn bind_schema(&self, id: LockerId, tag: &str) -> Result<()> {
        let key = schema_key(id);
        match self.backend.get(Table::Meta, &key).await? {
            Some(raw) => {
                let stored = String::from_utf8(raw)
                    .map_err(|e| Error::Corrupt(format!("schema tag is not UTF-8: {e}")))?;
                if stored != tag {
                    return Err(Error::SchemaMismatch {
                        stored,
                        requested: tag.to_string(),
                    });
                }
                Ok(())
            }
            None => {
                self.backend
                    .commit(vec![Op::Put {
                        table: Table::Meta,
                        key,
                        value: tag.as_bytes().to_vec(),
                    }])
                    .await
            }
        }
    }

    /// Every registered locker name, in registration-independent byte order.
    pub async fn locker_names(&self) -> Result<Vec<String>> {
        let mut names = Vec::new();
        let mut range = KeyRange::prefix(META_LOCKER_PREFIX);

        loop {
            let page = self
                .backend
                .scan(ScanRequest {
                    table: Table::Meta,
                    range: range.clone(),
                    reverse: false,
                    limit: 256,
                    want_values: false,
                })
                .await?;

            for (key, _) in &page.items {
                let raw = &key[META_LOCKER_PREFIX.len()..];
                names.push(
                    String::from_utf8(raw.to_vec())
                        .map_err(|e| Error::Corrupt(format!("locker name is not UTF-8: {e}")))?,
                );
            }

            match page.resume {
                Some(last) => range.start = std::ops::Bound::Excluded(last),
                None => break,
            }
        }

        Ok(names)
    }

    /// Build a throwaway `Inner` over an existing locker id.
    ///
    /// Only for bank-level maintenance that needs the record/chunk walk the
    /// lockers already own. It has its own watchers, so nothing it does is
    /// announced to a live locker's subscribers — deleting a locker out from
    /// under an open handle is refused instead.
    /// `chain` must be the locker's own chain, resolved with
    /// [`Bank::locker_chain`] — **not** the bank chain. A maintenance handle
    /// built over the wrong chain reads every record of a per-locker-chain
    /// locker as unopenable, which makes `verify` report the whole locker as
    /// corrupt and `quarantine` then delete all of it.
    fn maintenance_inner(&self, id: LockerId, name: &str, chain: Arc<FilterChain>) -> Arc<Inner> {
        Arc::new(Inner {
            write_lock: futures::lock::Mutex::new(()),
            backend: self.backend.clone(),
            chain,
            id,
            name: name.to_string(),
            config: LockerConfig::default(),
            shared: self.shared.clone(),
            watchers: Default::default(),
            closed: std::sync::atomic::AtomicBool::new(false),
            epochs: Default::default(),
            // A maintenance handle is a second view onto a name by
            // definition, and keeps no index at all. Nothing here may prove a
            // key absent.
            name_shared: std::sync::atomic::AtomicBool::new(true),
        })
    }

    /// Whether a locker has ever been registered under `name`.
    ///
    /// Registration, not content: a locker that was opened and never written
    /// to still exists. Hive's `boxExists`.
    pub async fn locker_exists(&self, name: &str) -> Result<bool> {
        if self.cached(name).is_some() {
            return Ok(true);
        }
        Ok(self
            .backend
            .get(Table::Meta, &locker_key(name))
            .await?
            .is_some())
    }

    /// Bytes stored for one locker: its records plus the chunks they point at.
    ///
    /// Measured by scanning, so the cost is proportional to the locker. It is
    /// the size of the *stored* — sealed, and compressed if the chain
    /// compresses — payloads, not of the values a caller put in, and it
    /// excludes key bytes and whatever the backend spends on its own
    /// bookkeeping. An unknown name is 0 rather than an error.
    pub async fn locker_bytes(&self, name: &str) -> Result<u64> {
        if !self.locker_exists(name).await? {
            return Ok(0);
        }
        let id = self.locker_id(name).await?;
        let chain = self.locker_chain_or_bank(id).await?;
        let inner = self.maintenance_inner(id, name, chain);

        let mut total: u64 = 0;
        let mut chunked: Vec<u64> = Vec::new();
        inner
            .walk(
                std::ops::Bound::Unbounded,
                std::ops::Bound::Unbounded,
                false,
                true,
                |_, value| {
                    if let Some(raw) = value {
                        total = total.saturating_add(raw.len() as u64);
                        // An unparseable pointer counts as the inline record
                        // it is indistinguishable from here; its raw length is
                        // already in `total`, and there are no chunks we can
                        // locate to add.
                        if crate::locker::chunk::is_pointer(&raw) {
                            if let Ok(pointer) = crate::locker::chunk::ChunkPointer::parse(&raw) {
                                chunked.push(pointer.value_id);
                            }
                        }
                    }
                    Ok(())
                },
            )
            .await?;

        for value_id in chunked {
            total = total.saturating_add(self.chunk_bytes(value_id).await?);
        }
        Ok(total)
    }

    /// Sum the stored chunk payloads for one chunked value.
    async fn chunk_bytes(&self, value_id: u64) -> Result<u64> {
        let mut range = crate::locker::chunk::chunk_range(value_id);
        let mut total: u64 = 0;
        loop {
            let page = self
                .backend
                .scan(ScanRequest {
                    table: Table::Chunks,
                    range: range.clone(),
                    reverse: false,
                    limit: 256,
                    want_values: true,
                })
                .await?;
            for (_, value) in &page.items {
                if let Some(bytes) = value {
                    total = total.saturating_add(bytes.len() as u64);
                }
            }
            match page.resume {
                Some(last) => range.start = std::ops::Bound::Excluded(last),
                None => break,
            }
        }
        Ok(total)
    }

    /// Read every record of a locker and report the keys that will not decode.
    ///
    /// The survey [`crate::Locker::corrupt_keys`] and
    /// [`LazyLocker::corrupt_keys`] cannot give you: it reads each record and,
    /// for a chunked value, every chunk behind it. Nothing is written and
    /// nothing is deleted — this is purely a question.
    ///
    /// It stops at the stored *payload*: a record whose bytes reassemble
    /// cleanly is reported as good even if the payload would then fail to
    /// deserialise into some particular `T`, because a bank does not know
    /// what type a locker holds. An unregistered name is an empty list rather
    /// than an error.
    ///
    /// Safe to run while the locker is open. It takes no locks and changes
    /// nothing, so the worst it can do is read a record a concurrent write is
    /// about to replace.
    ///
    /// Memory is bounded by the largest single value, not by the locker:
    /// inline records are checked in the walk, and only the chunk pointers are
    /// held back for the second pass.
    ///
    /// ```no_run
    /// use crossbank::{Bank, BankConfig};
    ///
    /// # async fn demo() -> crossbank::Result<()> {
    /// let bank = Bank::open(BankConfig::at("app.crossbank")).await?;
    ///
    /// // Survey first. Nothing is written and nothing is deleted.
    /// let bad = bank.verify("candles").await?;
    /// if !bad.is_empty() {
    ///     // Then, deliberately and by key, remove what a human decided to
    ///     // give up on. Every open handle must be closed first.
    ///     let keys: Vec<&[u8]> = bad.iter().map(|k| k.as_slice()).collect();
    ///     let removed = bank.quarantine("candles", &keys).await?;
    ///     println!("{removed} unreadable records removed");
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub async fn verify(&self, name: &str) -> Result<Vec<Vec<u8>>> {
        if !self.locker_exists(name).await? {
            return Ok(Vec::new());
        }
        let id = self.locker_id(name).await?;
        // The locker's own chain, never the bank's. Reading these records
        // through the wrong chain would report every single key as corrupt,
        // and the documented next step is to hand that list to
        // `quarantine` — which would delete the entire locker.
        let Some(chain) = self.locker_chain(id).await? else {
            let stored = self.stored_chain_id(id).await?;
            return Err(Error::SchemaMismatch {
                stored: format!(
                    "filter chain {}; nothing in this process can open it",
                    stored.map(|s| s.to_string()).unwrap_or_else(|| "?".into())
                ),
                requested: format!(
                    "locker {name:?} cannot be verified without its chain — register it \
                     with Bank::register_chain, or open the locker with it first"
                ),
            });
        };
        let inner = self.maintenance_inner(id, name, chain);

        let mut bad: Vec<Vec<u8>> = Vec::new();
        let mut chunked: Vec<(Vec<u8>, crate::locker::chunk::ChunkPointer)> = Vec::new();

        inner
            .walk(
                std::ops::Bound::Unbounded,
                std::ops::Bound::Unbounded,
                false,
                true,
                |key, value| {
                    let Some(raw) = value else {
                        bad.push(key);
                        return Ok(());
                    };
                    if crate::locker::chunk::is_pointer(&raw) {
                        match crate::locker::chunk::ChunkPointer::parse(&raw) {
                            Ok(pointer) => chunked.push((key, pointer)),
                            Err(_) => bad.push(key),
                        }
                    } else if inner.chain.open(&raw).is_err() {
                        bad.push(key);
                    }
                    Ok(())
                },
            )
            .await?;

        for (key, pointer) in chunked {
            if inner.read_chunks(&pointer).await.is_err() {
                bad.push(key);
            }
        }
        bad.sort();
        Ok(bad)
    }

    /// Delete exactly the named records of a locker, and their chunks.
    ///
    /// The **only** thing in crossbank that removes a record because it is
    /// corrupt. [`crate::OnCorrupt::Skip`] and [`Bank::verify`] both leave the
    /// stored bytes alone on purpose, so that a later build with a working
    /// decoder can still recover them; deletion has to be asked for, by key,
    /// after someone has looked.
    ///
    /// Returns how many of `keys` were actually present. Everything goes in
    /// **one** commit, so a failure leaves the locker as it was.
    ///
    /// Refuses with [`Error::InvalidConfig`] while a handle to the locker is
    /// open, exactly as [`Bank::delete_locker`] does and for the same reason:
    /// an open handle holds a RAM index that this would silently invalidate.
    /// [`Bank::verify`] has no such restriction — it changes nothing.
    pub async fn quarantine(&self, name: &str, keys: &[&[u8]]) -> Result<usize> {
        if self.is_locker_open(name) {
            return Err(Error::InvalidConfig(format!(
                "locker {name:?} is still open; close it before quarantining records"
            )));
        }
        if keys.is_empty() || !self.locker_exists(name).await? {
            return Ok(0);
        }

        let id = self.locker_id(name).await?;
        let chain = self.locker_chain_or_bank(id).await?;
        let inner = self.maintenance_inner(id, name, chain);

        let mut ops = Vec::new();
        let mut removed = 0usize;
        for key in keys {
            let Some(existing) = inner.fetch(key).await? else {
                continue;
            };
            if crate::locker::chunk::is_pointer(&existing) {
                // A pointer too broken to parse still has its record removed;
                // its chunks are unreachable either way.
                if let Ok(pointer) = crate::locker::chunk::ChunkPointer::parse(&existing) {
                    ops.push(crate::locker::chunk::gc_ops(&pointer));
                }
            }
            ops.push(inner.delete_op(key));
            removed += 1;
        }

        if !ops.is_empty() {
            self.backend.commit(ops).await?;
        }
        Ok(removed)
    }

    /// Delete a locker and everything it stores, permanently.
    ///
    /// Returns `false` if no locker was ever registered under `name`, so
    /// deleting a name twice is not an error. Hive's `deleteBoxFromDisk`.
    ///
    /// Refuses with [`Error::InvalidConfig`] while a handle to the locker is
    /// open. An open eager locker holds its values in RAM and an open lazy
    /// locker holds its key index, so deleting underneath either would leave a
    /// handle confidently serving data that no longer exists. Close it first.
    ///
    /// Records, the chunks they point at, the name registration and the schema
    /// tag all go in **one** commit, so a failure leaves the locker whole
    /// rather than half-erased.
    ///
    /// The locker's id is *not* recycled — `next_locker_id` only ever moves
    /// forward. Recreating the same name allocates a fresh id, which is what
    /// stops any record the delete somehow missed from being read as part of
    /// the new locker.
    pub async fn delete_locker(&self, name: &str) -> Result<bool> {
        if self.is_locker_open(name) {
            return Err(Error::InvalidConfig(format!(
                "locker {name:?} is still open; close it before deleting it"
            )));
        }
        if !self.locker_exists(name).await? {
            return Ok(false);
        }

        let id = self.locker_id(name).await?;
        let chain = self.locker_chain_or_bank(id).await?;
        let inner = self.maintenance_inner(id, name, chain);

        // The chunk GC ops and the record range deletion, exactly as `clear`
        // builds them, plus the two meta keys.
        let mut ops = inner.clear_value_ops().await?;
        ops.push(Op::Delete {
            table: Table::Meta,
            key: locker_key(name),
        });
        ops.push(Op::Delete {
            table: Table::Meta,
            key: schema_key(id),
        });
        self.backend.commit(ops).await?;

        if let Ok(mut guard) = self.registry.lock() {
            guard.remove(name);
        }
        if let Ok(mut guard) = self.open_lockers.lock() {
            guard.remove(name);
        }
        Ok(true)
    }

    /// Close the bank: release the backend handle.
    ///
    /// Idempotent. Every later operation — through this bank or through any
    /// locker still holding the same backend — reports [`Error::Closed`].
    ///
    /// This exists for close-then-reopen in a single process. `redb` holds an
    /// exclusive file lock for as long as its `Database` is alive, and the
    /// backend is shared through an `Arc`, so dropping the `Bank` is not
    /// enough to let the same file be opened again. Test suites reopen
    /// constantly; production code rarely closes at all.
    ///
    /// Lockers opened from this bank are *not* individually closed — they keep
    /// whatever they already hold in RAM, and their writes start failing.
    pub async fn close(&self) -> Result<()> {
        if self.is_closed() {
            return Ok(());
        }
        // Flush first, and close regardless of how that went: a caller who is
        // shutting down must not be left with an open bank because one batch
        // would not land. The flush error is still returned.
        let flushed = self.flush_all().await;
        if self.closed.swap(true, Ordering::AcqRel) {
            return flushed;
        }
        // Drop the message closure before the backend goes: a channel still
        // listening would call into a bank that no longer works.
        self.shared.coherence.close();
        let closed = self.backend.close().await;
        // The file is free again, so `delete_bank` may have it. Released even
        // when the backend's own close reported an error: the alternative is a
        // name nothing can ever delete.
        #[cfg(not(target_arch = "wasm32"))]
        self.release_tracked_path();
        flushed.and(closed)
    }

    /// Give up this bank's [`OPEN_BANKS`] entry, if it still holds one.
    ///
    /// Idempotent, and safe to call from `Drop`: it takes the path rather than
    /// reading it, so only the first caller removes anything.
    #[cfg(not(target_arch = "wasm32"))]
    fn release_tracked_path(&self) {
        let taken = match self.tracked_path.lock() {
            Ok(mut guard) => guard.take(),
            Err(_) => None,
        };
        if let Some(key) = taken {
            release_open_bank(&key);
        }
    }

    /// Whether [`Bank::close`] has been called.
    pub fn is_closed(&self) -> bool {
        self.closed.load(Ordering::Acquire)
    }

    fn register_resident(&self, resident: &Arc<crate::locker::resident::Resident>) {
        if let Ok(mut guard) = self.residents.lock() {
            guard.retain(|weak| weak.strong_count() > 0);
            guard.push(Arc::downgrade(resident));
        }
    }

    /// Commit every open locker's staged writes, then ask the backend to make
    /// what it holds durable.
    ///
    /// The answer to [`crate::Commit::Deferred`] at the application level:
    /// one call from a `pagehide` handler, or from a native stop hook,
    /// regardless of how many lockers are open. **crossbank spawns nothing,
    /// so nothing else will make this call for you.**
    ///
    /// A locker whose flush fails does not stop the others: every locker is
    /// flushed and the first error is returned, because on a shutdown path
    /// saving four lockers out of five beats saving none.
    pub async fn flush_all(&self) -> Result<()> {
        self.ensure_open()?;
        let residents: Vec<Arc<crate::locker::resident::Resident>> = match self.residents.lock() {
            Ok(mut guard) => {
                guard.retain(|weak| weak.strong_count() > 0);
                guard.iter().filter_map(|weak| weak.upgrade()).collect()
            }
            Err(_) => Vec::new(),
        };

        let mut first: Option<Error> = None;
        for resident in residents {
            if let Err(e) = resident.flush().await {
                first.get_or_insert(e);
            }
        }
        let flushed = self.backend.flush().await;
        match first {
            Some(e) => Err(e),
            None => flushed,
        }
    }

    /// Claim `name` for a freshly opened locker, or report who holds it.
    ///
    /// The claim is what the registry check in `locker_with` is not. That
    /// check runs, releases the lock, and then awaits `prepare` and `open`;
    /// two callers can both pass it and each build an `Inner`, a `Resident`
    /// and an index of their own, and whichever registered last used to
    /// **overwrite** the first — leaving a live locker no `is_locker_open`,
    /// `delete_locker` or later `locker(name)` could see, and two indexes on
    /// one name each willing to prove a key absent that the other had
    /// chunk-written (trap 27). So the last word on a name is spoken under
    /// the registry lock, after the awaits, and never before them.
    ///
    /// `Some` means somebody else won: the caller must discard the locker it
    /// just opened and hand out a view of the returned state instead. That
    /// locker has done nothing but read, so dropping it loses nothing.
    ///
    /// Both `Inner`s are marked `name_shared` when that happens. The loser is
    /// discarded, so nothing should be able to reach its index — the mark is
    /// the belt to that reasoning, and it costs only a read before a write.
    fn claim_open(&self, name: &str, open: OpenLocker) -> Option<Shared> {
        let mut guard = self.open_lockers.lock().ok()?;
        Self::prune(&mut guard);
        if let Some(winner) = guard.get(name).and_then(OpenLocker::upgrade) {
            winner.inner.mark_name_shared();
            if let Some(mine) = open.inner.upgrade() {
                mine.mark_name_shared();
            }
            return Some(winner);
        }
        guard.insert(name.to_string(), open);
        None
    }

    /// The live state behind `name`, if this bank still has it open.
    fn open_locker(&self, name: &str) -> Option<Shared> {
        let mut guard = self.open_lockers.lock().ok()?;
        Self::prune(&mut guard);
        guard.get(name)?.upgrade()
    }

    /// Refuse a second handle whose open would mean something different from
    /// the first one's.
    ///
    /// Sharing is only safe while both handles agree about what the locker
    /// *is*. A different value type would decode one handle's writes into
    /// plausible garbage for the other; a different config would mean one
    /// handle's rules silently governing the other's writes.
    fn check_shared<T>(
        name: &str,
        open: &Shared,
        kind: TxMode,
        config: &LockerConfig,
    ) -> Result<()> {
        if open.kind != kind {
            return Err(Error::SchemaMismatch {
                stored: format!("{} locker {name:?}", kind_word(open.kind)),
                requested: format!("{} locker {name:?}", kind_word(kind)),
            });
        }
        let requested = type_tag::<T>();
        if open.type_tag != requested {
            return Err(Error::SchemaMismatch {
                stored: open.type_tag.clone(),
                requested,
            });
        }
        if let Some(field) = config_conflict(&open.config, config) {
            return Err(Error::InvalidConfig(format!(
                "locker {name:?} is already open with a different {field}; every handle on \
                 one name shares its state, so they must be opened the same way. Close the \
                 open handle first, or open this one with the same config."
            )));
        }
        Ok(())
    }

    /// Whether a locker is currently open under `name`.
    ///
    /// A locker counts as open while a handle to it is alive and has not had
    /// `close()` called on it. Dropped handles stop counting on the next read
    /// of this registry.
    ///
    /// Opening the same name twice is **allowed** and hands out another view
    /// of the same open locker (see [`Bank::locker_with`]). The name counts as
    /// open until every one of those handles is dropped — or until any one of
    /// them is closed, which closes the locker for all of them.
    pub fn is_locker_open(&self, name: &str) -> bool {
        let Ok(mut guard) = self.open_lockers.lock() else {
            return false;
        };
        Self::prune(&mut guard);
        guard.contains_key(name)
    }

    /// Every locker name with a live, unclosed handle, in byte order.
    pub fn open_locker_names(&self) -> Vec<String> {
        let Ok(mut guard) = self.open_lockers.lock() else {
            return Vec::new();
        };
        Self::prune(&mut guard);
        let mut names: Vec<String> = guard.keys().cloned().collect();
        names.sort();
        names
    }

    /// Drop names whose last handle is gone, or that have been closed.
    fn prune(map: &mut HashMap<String, OpenLocker>) {
        map.retain(|_, open| match open.inner.upgrade() {
            Some(inner) => !inner.is_closed(),
            None => false,
        });
    }

    fn cached(&self, name: &str) -> Option<LockerId> {
        self.registry.lock().ok()?.get(name).copied()
    }

    fn cache(&self, name: &str, id: LockerId) {
        if let Ok(mut guard) = self.registry.lock() {
            guard.insert(name.to_string(), id);
        }
    }
}

/// Every native bank file this process currently holds open.
///
/// `delete_bank` consults it before unlinking. Without that check, deleting a
/// bank that is still open removes the *name* on Unix while `redb` keeps
/// writing into the now-nameless file, so every later commit is lost with no
/// error anywhere; on Windows the unlink instead fails with an opaque
/// permission error. Both are refusals in disguise, so we refuse honestly.
///
/// Keyed by the canonicalised path, so two spellings of one file are one
/// entry. Only banks opened through [`Bank::open`] (that is, a
/// [`BankConfig::at`] location) are in here; see the note on
/// [`Bank::with_backend`] in `delete_bank`'s own documentation.
#[cfg(not(target_arch = "wasm32"))]
static OPEN_BANKS: std::sync::OnceLock<Mutex<std::collections::HashSet<std::path::PathBuf>>> =
    std::sync::OnceLock::new();

#[cfg(not(target_arch = "wasm32"))]
fn open_banks() -> &'static Mutex<std::collections::HashSet<std::path::PathBuf>> {
    OPEN_BANKS.get_or_init(|| Mutex::new(std::collections::HashSet::new()))
}

/// The registry key for a bank location.
///
/// `canonicalize` is the one that collapses symlinks and `..`, but it needs the
/// file to exist; a location whose file is not there yet falls back to the
/// absolute path, which is still stable for one process.
#[cfg(not(target_arch = "wasm32"))]
fn bank_key(path: &std::path::Path) -> std::path::PathBuf {
    std::fs::canonicalize(path)
        .or_else(|_| std::path::absolute(path))
        .unwrap_or_else(|_| path.to_path_buf())
}

#[cfg(not(target_arch = "wasm32"))]
fn register_open_bank(key: std::path::PathBuf) {
    if let Ok(mut guard) = open_banks().lock() {
        guard.insert(key);
    }
}

#[cfg(not(target_arch = "wasm32"))]
fn release_open_bank(key: &std::path::Path) {
    if let Ok(mut guard) = open_banks().lock() {
        guard.remove(key);
    }
}

#[cfg(not(target_arch = "wasm32"))]
fn bank_is_open(key: &std::path::Path) -> bool {
    match open_banks().lock() {
        Ok(guard) => guard.contains(key),
        // A poisoned registry cannot prove the bank is closed, and guessing
        // wrong here costs the caller their data. Refuse.
        Err(_) => true,
    }
}

/// Delete a whole bank from the platform it lives on.
///
/// Idempotent: deleting a location that holds nothing succeeds. **Every handle
/// onto that location must be closed first**, and this refuses rather than
/// letting you find out later — natively `redb` still holds an exclusive lock
/// on an open file, and on the web an open IndexedDB connection blocks the
/// delete until it goes away.
///
/// Deleting a native bank that is still open is [`Error::InvalidConfig`]
/// saying *close the bank first*, and nothing is removed. The refusal matters:
/// Unix would happily unlink the file out from under `redb`'s open descriptor,
/// leaving a live `Bank` committing into a file with no name, so every write
/// after the delete would be lost silently. A bank counts as open until
/// [`Bank::close`] returns or the `Bank` is dropped — a dropped-but-never-closed
/// bank frees the name too.
///
/// Only banks opened through [`Bank::open`] / [`BankConfig::at`] are tracked. A
/// bank built with [`Bank::with_backend`] over a hand-made
/// `RedbBackend` is invisible here, and deleting its file while it lives is the
/// unlink-under-a-live-fd hazard again.
///
/// A free function rather than a method, because a `Bank` you are about to
/// erase is not a good place to hang the erasing from.
pub async fn delete_bank(config: &BankConfig) -> Result<()> {
    match &config.location {
        // Nothing outlives the handles; there is no location to erase.
        Location::Memory => Ok(()),
        Location::Path(path) => {
            #[cfg(not(target_arch = "wasm32"))]
            {
                if bank_is_open(&bank_key(path)) {
                    return Err(Error::InvalidConfig(format!(
                        "the bank at {} is still open in this process; \
                         close the bank first",
                        path.display()
                    )));
                }
                match std::fs::remove_file(path) {
                    Ok(()) => Ok(()),
                    Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
                    // What an externally held lock looks like on Windows: the
                    // same "it is still open" answer, not a backend fault.
                    Err(e) if cfg!(windows) && e.kind() == std::io::ErrorKind::PermissionDenied => {
                        Err(Error::InvalidConfig(format!(
                            "the bank file {} is held open by something else; \
                             close the bank first",
                            path.display()
                        )))
                    }
                    Err(e) => Err(Error::backend(format!(
                        "deleting the bank file {}: {e}",
                        path.display()
                    ))),
                }
            }
            #[cfg(target_arch = "wasm32")]
            {
                let _ = path;
                Err(Error::InvalidConfig(
                    "Location::Path is native-only; use Location::Web on wasm".into(),
                ))
            }
        }
        Location::Web(name) => {
            #[cfg(target_arch = "wasm32")]
            {
                crate::backend::IndexedDbBackend::delete_database(name).await
            }
            #[cfg(not(target_arch = "wasm32"))]
            {
                let _ = name;
                Err(Error::InvalidConfig(
                    "Location::Web is wasm-only; use Location::Path on native".into(),
                ))
            }
        }
    }
}

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

    /// The coherence flag is accepted everywhere and refuses nothing.
    ///
    /// Natively it does nothing at all — `redb` takes an exclusive file lock,
    /// so there is no second process to stay in step with — but a consumer
    /// must be able to set it once and compile for both targets.
    #[test]
    fn the_coherence_flag_is_accepted_and_native_ignores_it() {
        let config = BankConfig::memory().with_coherence(true);
        assert!(config.coherence);
        assert!(!BankConfig::memory().coherence, "never on by default");

        let bank = block_on(Bank::open(config)).unwrap();
        let locker = block_on(bank.lazy_locker::<String>("l")).unwrap();
        block_on(locker.put("k", &"v".to_string())).unwrap();
        assert_eq!(block_on(locker.get("k")).unwrap(), Some("v".to_string()));
        block_on(bank.close()).unwrap();
    }
    use crate::backend::MemoryBackend;
    use futures::executor::block_on;

    fn bank() -> Bank {
        block_on(Bank::with_backend(Arc::new(MemoryBackend::new()))).unwrap()
    }

    /// Replace a stored record's bytes with something no decoder can read.
    fn corrupt_record(bank: &Bank, id: LockerId, key: &str) {
        block_on(bank.backend().commit(vec![Op::Put {
            table: Table::Records,
            key: crate::key::encode(id, key),
            value: b"not a CBNK envelope".to_vec(),
        }]))
        .unwrap();
    }

    #[test]
    fn a_corrupt_record_can_be_skipped_verified_and_quarantined() {
        use crate::locker::OnCorrupt;

        let b = bank();
        let l = block_on(b.locker::<String>("l")).unwrap();
        block_on(l.put("good", "keep".into())).unwrap();
        block_on(l.put("bad", "lose".into())).unwrap();
        let id = block_on(b.locker_id("l")).unwrap();
        block_on(l.close()).unwrap();

        corrupt_record(&b, id, "bad");

        // The default refuses to open at all rather than serving a half view.
        assert!(matches!(
            block_on(b.locker::<String>("l")),
            Err(Error::Corrupt(_))
        ));

        // Asked to skip, it opens, names the casualty, and leaves it on disk.
        let skipping = block_on(b.locker_with::<String>(
            "l",
            LockerConfig::default().with_on_corrupt(OnCorrupt::Skip),
        ))
        .unwrap();
        assert_eq!(skipping.corrupt_keys(), vec![b"bad".to_vec()]);
        assert!(skipping.get("bad").is_none());
        assert_eq!(skipping.get("good").as_deref(), Some(&"keep".to_string()));
        assert_eq!(skipping.len(), 1);

        // verify surveys the same damage, and runs happily while open.
        assert_eq!(block_on(b.verify("l")).unwrap(), vec![b"bad".to_vec()]);

        // quarantine will not act behind an open handle.
        assert!(matches!(
            block_on(b.quarantine("l", &[b"bad"])),
            Err(Error::InvalidConfig(_))
        ));
        block_on(skipping.close()).unwrap();

        assert_eq!(block_on(b.quarantine("l", &[b"bad"])).unwrap(), 1);
        assert!(block_on(b.verify("l")).unwrap().is_empty());

        // And now the strict open succeeds again, with the good record intact.
        let healed = block_on(b.locker::<String>("l")).unwrap();
        assert_eq!(healed.len(), 1);
        assert_eq!(healed.get("good").as_deref(), Some(&"keep".to_string()));
    }

    #[test]
    fn quarantining_an_absent_key_removes_nothing() {
        let b = bank();
        let l = block_on(b.lazy_locker::<String>("l")).unwrap();
        block_on(l.put("k", &"v".to_string())).unwrap();
        block_on(l.close()).unwrap();

        assert_eq!(block_on(b.quarantine("l", &[b"ghost"])).unwrap(), 0);
        assert_eq!(block_on(b.quarantine("l", &[])).unwrap(), 0);
        assert_eq!(
            block_on(b.quarantine("never_registered", &[b"k"])).unwrap(),
            0
        );

        let reopened = block_on(b.lazy_locker::<String>("l")).unwrap();
        assert_eq!(reopened.len(), 1);
    }

    #[test]
    fn verifying_an_unknown_locker_is_empty_not_an_error() {
        let b = bank();
        assert!(block_on(b.verify("never_registered")).unwrap().is_empty());
    }

    #[test]
    fn a_lazy_get_reports_corruption_even_when_skipping() {
        // Skip governs OPEN. Answering a direct read with `None` would claim
        // the key was never written, which is a lie about bytes still on disk.
        use crate::locker::OnCorrupt;

        let b = bank();
        let l = block_on(b.lazy_locker::<String>("l")).unwrap();
        block_on(l.put("bad", &"v".to_string())).unwrap();
        let id = block_on(b.locker_id("l")).unwrap();
        block_on(l.close()).unwrap();
        corrupt_record(&b, id, "bad");

        let skipping = block_on(b.lazy_locker_with::<String>(
            "l",
            LockerConfig::default().with_on_corrupt(OnCorrupt::Skip),
        ))
        .unwrap();
        assert!(skipping.corrupt_keys().is_empty(), "nothing read yet");

        assert!(block_on(skipping.get("bad")).is_err());
        assert_eq!(skipping.corrupt_keys(), vec![b"bad".to_vec()]);
        // The key is still indexed: it exists, it just cannot be read.
        assert!(skipping.contains_key("bad"));
    }

    #[test]
    fn ids_are_stable_across_lookups() {
        let b = bank();
        let first = block_on(b.locker_id("settings")).unwrap();
        let again = block_on(b.locker_id("settings")).unwrap();
        assert_eq!(first, again);
    }

    #[test]
    fn distinct_names_get_distinct_ids() {
        let b = bank();
        let a = block_on(b.locker_id("a")).unwrap();
        let c = block_on(b.locker_id("b")).unwrap();
        assert_ne!(a, c);
    }

    #[test]
    fn ids_survive_reopening_over_the_same_backend() {
        // The registry cache must not be the source of truth, or a second
        // handle would allocate fresh ids over existing data.
        let backend: Arc<dyn Backend> = Arc::new(MemoryBackend::new());

        let first = block_on(Bank::with_backend(backend.clone())).unwrap();
        let settings = block_on(first.locker_id("settings")).unwrap();
        let candles = block_on(first.locker_id("candles")).unwrap();
        drop(first);

        let second = block_on(Bank::with_backend(backend)).unwrap();
        assert_eq!(block_on(second.locker_id("settings")).unwrap(), settings);
        assert_eq!(block_on(second.locker_id("candles")).unwrap(), candles);
    }

    #[test]
    fn a_fresh_name_after_reopen_does_not_reuse_an_id() {
        // Reusing an id would make a stale key readable as a different
        // locker's, which is the failure a persisted counter prevents.
        let backend: Arc<dyn Backend> = Arc::new(MemoryBackend::new());

        let first = block_on(Bank::with_backend(backend.clone())).unwrap();
        let a = block_on(first.locker_id("a")).unwrap();
        let b_id = block_on(first.locker_id("b")).unwrap();
        drop(first);

        let second = block_on(Bank::with_backend(backend)).unwrap();
        let c = block_on(second.locker_id("c")).unwrap();
        assert_ne!(c, a);
        assert_ne!(c, b_id);
    }

    #[test]
    fn locker_names_lists_every_registration() {
        let b = bank();
        for name in ["ui_settings", "candle_cache", "reports"] {
            block_on(b.locker_id(name)).unwrap();
        }

        let mut names = block_on(b.locker_names()).unwrap();
        names.sort();
        assert_eq!(names, vec!["candle_cache", "reports", "ui_settings"]);
    }

    #[test]
    fn locker_names_pages_past_one_scan_page() {
        // The registry scan pages at 256; prove the loop actually continues.
        let b = bank();
        for i in 0..300 {
            block_on(b.locker_id(&format!("locker_{i:04}"))).unwrap();
        }
        assert_eq!(block_on(b.locker_names()).unwrap().len(), 300);
    }

    #[test]
    fn a_locker_name_may_contain_awkward_bytes() {
        let b = bank();
        let weird = "name with spaces :: and 🍎";
        block_on(b.locker_id(weird)).unwrap();
        assert_eq!(block_on(b.locker_names()).unwrap(), vec![weird]);
    }

    #[test]
    fn binding_the_same_schema_twice_is_fine() {
        let b = bank();
        let id = block_on(b.locker_id("x")).unwrap();
        block_on(b.bind_schema(id, "Settings")).unwrap();
        block_on(b.bind_schema(id, "Settings")).unwrap();
    }

    #[test]
    fn rebinding_a_different_schema_is_refused() {
        // The guard against opening Locker<A> over data written as Locker<B>.
        let b = bank();
        let id = block_on(b.locker_id("x")).unwrap();
        block_on(b.bind_schema(id, "Settings")).unwrap();

        match block_on(b.bind_schema(id, "ReportMeta")) {
            Err(Error::SchemaMismatch { stored, requested }) => {
                assert_eq!(stored, "Settings");
                assert_eq!(requested, "ReportMeta");
            }
            other => panic!("expected a schema mismatch, got {other:?}"),
        }
    }

    #[test]
    fn schemas_are_per_locker_not_global() {
        let b = bank();
        let one = block_on(b.locker_id("one")).unwrap();
        let two = block_on(b.locker_id("two")).unwrap();
        block_on(b.bind_schema(one, "Settings")).unwrap();
        block_on(b.bind_schema(two, "ReportMeta")).unwrap();
    }

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

        let first = block_on(Bank::with_backend(backend.clone())).unwrap();
        let settings = block_on(first.locker::<String>("ui_settings")).unwrap();
        block_on(settings.put("theme", "dark".into())).unwrap();

        let candles = block_on(first.lazy_locker::<String>("candle_cache")).unwrap();
        block_on(candles.put("BTCUSDT::1", &"ohlc".to_string())).unwrap();
        drop(first);

        let second = block_on(Bank::with_backend(backend)).unwrap();
        let settings = block_on(second.locker::<String>("ui_settings")).unwrap();
        assert_eq!(settings.get("theme").as_deref(), Some(&"dark".to_string()));

        let candles = block_on(second.lazy_locker::<String>("candle_cache")).unwrap();
        assert_eq!(
            block_on(candles.get("BTCUSDT::1")).unwrap(),
            Some("ohlc".into())
        );
    }

    #[test]
    fn two_lockers_do_not_see_each_other() {
        let b = bank();
        let one = block_on(b.locker::<String>("one")).unwrap();
        let two = block_on(b.locker::<String>("two")).unwrap();

        block_on(one.put("k", "from one".into())).unwrap();
        block_on(two.put("k", "from two".into())).unwrap();

        assert_eq!(one.get("k").as_deref(), Some(&"from one".to_string()));
        assert_eq!(two.get("k").as_deref(), Some(&"from two".to_string()));
    }

    #[test]
    fn reopening_a_locker_as_a_different_type_is_refused() {
        // The schema guard, exercised end to end through the public API.
        let b = bank();
        block_on(b.locker::<String>("x")).unwrap();

        match block_on(b.locker::<u64>("x")) {
            Err(Error::SchemaMismatch { .. }) => {}
            other => panic!("expected a schema mismatch, got {:?}", other.map(|_| "ok")),
        }
    }

    #[test]
    fn a_future_format_version_is_refused() {
        let backend: Arc<dyn Backend> = Arc::new(MemoryBackend::new());
        block_on(backend.commit(vec![Op::Put {
            table: Table::Meta,
            key: META_FORMAT_VERSION.to_vec(),
            value: (FORMAT_VERSION + 1).to_be_bytes().to_vec(),
        }]))
        .unwrap();

        assert!(matches!(
            block_on(Bank::with_backend(backend)),
            Err(Error::UnsupportedVersion { .. })
        ));
    }

    #[test]
    fn open_memory_round_trips() {
        let bank = block_on(Bank::open(BankConfig::memory())).unwrap();
        let locker = block_on(bank.locker::<String>("ui_settings")).unwrap();
        block_on(locker.put("theme", "dark".into())).unwrap();
        assert_eq!(locker.get("theme").as_deref(), Some(&"dark".to_string()));
    }

    #[test]
    fn open_web_is_refused_on_native() {
        match block_on(Bank::open(BankConfig::web("should-not-open"))) {
            Err(Error::InvalidConfig(msg)) => {
                assert!(msg.contains("wasm-only"), "{msg}");
            }
            other => panic!("expected InvalidConfig, got {other:?}"),
        }
    }

    #[cfg(not(target_arch = "wasm32"))]
    #[test]
    fn open_path_persists_across_handles() {
        let dir = tempfile::TempDir::new().unwrap();
        let path = dir.path().join("bank.redb");

        {
            let bank = block_on(Bank::open(BankConfig::at(&path))).unwrap();
            let locker = block_on(bank.locker::<String>("ui_settings")).unwrap();
            block_on(locker.put("theme", "dark".into())).unwrap();
        }

        let bank = block_on(Bank::open(BankConfig::at(&path))).unwrap();
        let locker = block_on(bank.locker::<String>("ui_settings")).unwrap();
        assert_eq!(locker.get("theme").as_deref(), Some(&"dark".to_string()));
    }

    #[cfg(not(target_arch = "wasm32"))]
    #[test]
    fn delete_bank_removes_the_file_and_tolerates_a_missing_one() {
        let dir = tempfile::TempDir::new().unwrap();
        let path = dir.path().join("bank.redb");
        let config = BankConfig::at(&path);

        let bank = block_on(Bank::open(config.clone())).unwrap();
        let locker = block_on(bank.locker::<String>("s")).unwrap();
        block_on(locker.put("k", "v".into())).unwrap();
        // redb still holds the file open until the bank is closed.
        block_on(bank.close()).unwrap();

        block_on(delete_bank(&config)).unwrap();
        assert!(!path.exists());

        // Idempotent: a location holding nothing is not an error.
        block_on(delete_bank(&config)).unwrap();

        let reborn = block_on(Bank::open(config)).unwrap();
        let locker = block_on(reborn.locker::<String>("s")).unwrap();
        assert_eq!(locker.get("k"), None, "the data went with the file");
    }

    /// The whole point of the open-bank registry.
    ///
    /// Unix will unlink a file `redb` still has open, and the `Bank` on the
    /// other side keeps committing into something with no name — every write
    /// after the delete is lost, with no error anywhere. Refusing is the only
    /// honest answer, and the refusal must leave the store completely intact.
    #[cfg(not(target_arch = "wasm32"))]
    #[test]
    fn delete_bank_refuses_while_the_bank_is_open() {
        let dir = tempfile::TempDir::new().unwrap();
        let path = dir.path().join("live.redb");
        let config = BankConfig::at(&path);

        let bank = block_on(Bank::open(config.clone())).unwrap();
        let locker = block_on(bank.locker::<String>("s")).unwrap();
        block_on(locker.put("k", "v".into())).unwrap();

        let refused = block_on(delete_bank(&config));
        match refused {
            Err(Error::InvalidConfig(msg)) => assert!(
                msg.contains("close the bank first"),
                "the error must say what to do instead: {msg}"
            ),
            other => panic!("deleting an open bank must be refused, got {other:?}"),
        }

        // Nothing was touched, and the bank is still fully usable.
        assert!(path.exists(), "the refusal must not remove the file");
        block_on(locker.put("k2", "v2".into())).unwrap();
        assert_eq!(locker.get("k").as_deref(), Some(&"v".to_string()));

        // Closing frees the name, and the write made after the refusal is
        // really on disk rather than in a file nobody can find.
        block_on(bank.close()).unwrap();
        block_on(delete_bank(&config)).unwrap();
        assert!(!path.exists());
    }

    /// A bank that is merely dropped never runs `close`, but it does run
    /// `Drop`, and the file is just as free afterwards.
    #[cfg(not(target_arch = "wasm32"))]
    #[test]
    fn dropping_a_bank_without_closing_it_frees_the_name() {
        let dir = tempfile::TempDir::new().unwrap();
        let path = dir.path().join("dropped.redb");
        let config = BankConfig::at(&path);

        {
            let bank = block_on(Bank::open(config.clone())).unwrap();
            let locker = block_on(bank.locker::<String>("s")).unwrap();
            block_on(locker.put("k", "v".into())).unwrap();
            assert!(block_on(delete_bank(&config)).is_err(), "still open here");
        }

        block_on(delete_bank(&config)).unwrap();
        assert!(!path.exists());
    }

    /// Two spellings of one file are one entry: the registry canonicalises.
    #[cfg(not(target_arch = "wasm32"))]
    #[test]
    fn the_open_registry_sees_through_a_roundabout_path() {
        let dir = tempfile::TempDir::new().unwrap();
        let path = dir.path().join("twisty.redb");
        let bank = block_on(Bank::open(BankConfig::at(&path))).unwrap();

        let roundabout = dir.path().join("sub").join("..").join("twisty.redb");
        std::fs::create_dir_all(dir.path().join("sub")).unwrap();
        assert!(
            block_on(delete_bank(&BankConfig::at(&roundabout))).is_err(),
            "the same file spelled differently is the same open bank"
        );

        block_on(bank.close()).unwrap();
    }

    #[cfg(not(target_arch = "wasm32"))]
    #[test]
    fn delete_bank_refuses_a_web_location_on_native() {
        assert!(matches!(
            block_on(delete_bank(&BankConfig::web("nope"))),
            Err(Error::InvalidConfig(_))
        ));
    }

    #[test]
    fn deleting_a_memory_bank_is_a_no_op() {
        block_on(delete_bank(&BankConfig::memory())).unwrap();
    }
}