rca-sharing 0.1.0

Share values and read-only projections between Rust components without a Store or runtime
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
//! Caches weak typed references inside an explicitly owned namespace.
//!
//! Fresh ordinary construction evaluates its seed before initial loading, even
//! when storage contains a value. A live compatible hit does no seed, load or
//! subscription work. Require always loads first and rejects storage absence;
//! its loaded value may then lose to an existing live reference.
//!
//! Constructors check, build outside the cache lock, then check again. Racing
//! candidates may both seed, load and subscribe; one live publication wins and
//! the losing subscription is dropped outside the lock. There is no exactly-once
//! provider guarantee. Reset removes lookup entries, not storage, existing
//! handles or in-flight constructors; a later publication can repopulate it.
//!
//! Initial load borrows the seed. Subscription context records initial versus
//! user intent, without duplicating a move-only seed. Unlike Swift Sharing, a
//! subscription does not automatically restore a captured original default.
//! Producer absence, conflict handling, persistence ordering and Store action
//! delivery are separate policies, not supplied by this cache.
//!
//! Loading and subscribing are separate provider calls. A non-replaying provider
//! can miss an update between them; construction does not promise a continuous
//! snapshot or an event history. Providers requiring continuity must supply
//! replay, atomic snapshot/registration or revision reconciliation themselves.
//! Synchronous subscription delivery may replace the initially loaded value or
//! seed before construction returns.
//!
//! Only cache admission requires `Value: Send + 'static`; no `Sync`, `Clone` or
//! `Debug` is required of values. General in-memory [`Shared`] remains usable
//! with local values. Provider identities and callbacks run outside the cache
//! lock. Looking up, inserting, or clearing entries can wait for that lock.
//! Value access keeps the ordinary non-blocking shared-value access contract.
//!
//! Reloads arbitrate on their captured reference: the latest started request
//! alone may commit, even when it completes absent, fails or is cancelled.
//! Superseded callers still receive their own provider errors, but cannot
//! replace the current value. Successful producer delivery also supersedes
//! earlier reloads; failed delivery leaves their authority unchanged. Producer
//! ordering, absence and conflict rules remain separate policies.

use std::any::{Any, TypeId};
use std::collections::HashMap;
use std::convert::Infallible;
use std::fmt;
use std::sync::{Arc, Mutex, Weak};

use super::{Shared, SharedAccessError, SharedReader, SharedReference, try_lock};

/// Identifies a resource and its codec configuration within one cache namespace.
#[derive(Clone, Eq, PartialEq)]
pub struct SharedKeyIdentity {
    /// Names the resource within a cache namespace, including backend identity.
    address: String,
    /// Distinguishes incompatible codec implementations at the same address.
    codec: TypeId,
    /// Distinguishes incompatible settings of the same codec implementation.
    configuration: String,
}

impl SharedKeyIdentity {
    /// Creates a stable address with explicit codec type and configuration.
    ///
    /// Equal addresses must designate the same resource. Include backend/store
    /// identity in the address when one cache serves multiple stores. Codec
    /// configuration must distinguish incompatible instances of the same type.
    #[must_use]
    pub fn new<Codec: 'static>(
        address: impl Into<String>,
        configuration: impl Into<String>,
    ) -> Self {
        Self {
            address: address.into(),
            codec: TypeId::of::<Codec>(),
            configuration: configuration.into(),
        }
    }
}

impl fmt::Debug for SharedKeyIdentity {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("SharedKeyIdentity").finish_non_exhaustive()
    }
}

/// Distinguishes a borrowed construction seed from an explicit storage load.
pub enum SharedLoadContext<'a, Value> {
    /// Initial construction borrows its already evaluated seed.
    Initial(&'a Value),
    /// Explicit require or reload supplies no default.
    UserInitiated,
}

impl<Value> fmt::Debug for SharedLoadContext<'_, Value> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            Self::Initial(_) => "SharedLoadContext::Initial(..)",
            Self::UserInitiated => "SharedLoadContext::UserInitiated",
        })
    }
}

/// Identifies subscription intent without retaining a duplicate seed value.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum SharedSubscribeContext {
    /// Ordinary seeded construction follows its initial load.
    Initial,
    /// Require or key replacement skips an implicit initial load.
    UserInitiated,
}

/// Supplies typed loading and an owned subscription for a stable resource.
///
/// Implementations must keep identity stable and represent absence as outer
/// `None`, independently of a stored optional value. Subscription guards must
/// release their provider registration on drop. Retain the supplied weak
/// subscriber, not an independently captured strong handle to its owner.
/// Loading before subscribing does not itself prevent missed updates. Specify
/// the provider's replay, registration and absence rules when stronger continuity
/// is required; successful subscription setup is not necessarily delivery acknowledgement.
pub trait SharedReaderKey: Send + Sync + 'static {
    /// Value admitted to the heterogeneous cache.
    type Value: Send + 'static;
    /// Original provider failure, without a required formatting trait.
    type Error;
    /// Resource retained until the final captured reference is dropped.
    type Subscription: Send + Sync + 'static;

    /// Returns the stable resource and codec compatibility identity.
    fn identity(&self) -> SharedKeyIdentity;

    /// Loads storage, keeping a missing value distinct from a provider failure.
    ///
    /// # Errors
    /// Returns the original provider failure.
    fn load(
        &self,
        context: SharedLoadContext<'_, Self::Value>,
    ) -> impl Future<Output = Result<Option<Self::Value>, Self::Error>> + Send;

    /// Starts owned producer delivery without holding a cache or value lock.
    ///
    /// # Errors
    /// Returns the original subscription failure; construction is not published.
    fn subscribe(
        &self,
        context: SharedSubscribeContext,
        subscriber: SharedSubscriber<Self::Value>,
    ) -> Result<Self::Subscription, Self::Error>;
}

/// Adds explicit saving capability to a typed readable resource.
///
/// Cache-backed mutation uses ordinary [`Shared::try_update`] and its explicit
/// publication callback. This trait does not install automatic saving, flush
/// barriers, coalescing, rollback or a runtime.
pub trait SharedKey: SharedReaderKey {
    /// Saves a borrowed value using the provider's own completion guarantee.
    ///
    /// # Errors
    /// Returns the original encoding or provider failure.
    fn save(&self, value: &Self::Value) -> impl Future<Output = Result<(), Self::Error>> + Send;
}

/// Delivers owned values through a weak captured reference.
pub struct SharedSubscriber<Value> {
    /// Targets only the original captured value; never resolves a new cache hit.
    reference: Weak<SharedReference<Value>>,
    /// Shares reload ordering without keeping its resource alive.
    loads: Weak<Mutex<Option<Weak<()>>>>,
}

impl<Value> SharedSubscriber<Value> {
    /// Replaces a live value, returning false after its final owner has gone.
    ///
    /// This conveys data only, not Store scope or action-delivery authority.
    /// Successful replacement supersedes already started reloads atomically.
    /// Displaced values are dropped after releasing both internal locks.
    ///
    /// # Errors
    /// Returns Busy or Poisoned without applying the value or superseding a reload.
    ///
    /// # Panics
    /// A displaced value's destructor may panic after replacement. It runs
    /// after releasing both internal locks.
    pub fn yield_value(&self, mut value: Value) -> Result<bool, SharedAccessError> {
        self.prepare_publication()
            .map_or(Ok(false), |publication| publication.try_replace(&mut value))
    }

    /// Retains this captured reference for one externally fenced publication.
    ///
    /// Prepare before acquiring a caller-owned cancellation fence. Release that
    /// fence before dropping this owner or the displaced value. Preparation does
    /// not grant Store, session or subscription authority and never finds a new
    /// reference by logical identity. Returns None after the captured resource ends.
    #[must_use]
    pub fn prepare_publication(&self) -> Option<SharedPublication<Value>> {
        Some(SharedPublication {
            reference: self.reference.upgrade()?,
            loads: self.loads.upgrade()?,
        })
    }
}

/// Briefly retains one captured reference and its reload coordinator.
///
/// Drop this prepared owner outside external control fences: it may be the final
/// reference owner, whose value/resource destructors can run arbitrary code.
#[must_use]
pub struct SharedPublication<Value> {
    /// Retains the exact captured owner through an externally fenced swap.
    reference: Arc<SharedReference<Value>>,
    /// Lets successful producer delivery retire earlier reloads atomically.
    loads: Arc<Mutex<Option<Weak<()>>>>,
}

impl<Value> SharedPublication<Value> {
    /// Swaps the captured value with the caller's value without dropping either.
    ///
    /// On success the slot contains the displaced value; otherwise it is unchanged.
    /// This lets an external cancellation owner hold its commit fence over the
    /// swap, then release that fence before dropping the displaced value. No user
    /// callback or value destructor runs here. Successful swaps supersede reloads.
    ///
    /// # Errors
    /// Returns Busy or Poisoned without changing the slot or reload authority.
    pub fn try_replace(&self, value: &mut Value) -> Result<bool, SharedAccessError> {
        let retired = {
            let mut latest = self.loads.lock().map_err(|_error| load_poisoned())?;
            let mut current = try_lock(&self.reference.value)?;
            std::mem::swap(&mut *current, value);
            latest.take()
        };
        drop(retired);
        Ok(true)
    }
}

impl<Value> fmt::Debug for SharedPublication<Value> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("SharedPublication").finish_non_exhaustive()
    }
}

impl<Value> Clone for SharedSubscriber<Value> {
    fn clone(&self) -> Self {
        Self {
            reference: Weak::clone(&self.reference),
            loads: Weak::clone(&self.loads),
        }
    }
}

impl<Value> fmt::Debug for SharedSubscriber<Value> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("SharedSubscriber").finish_non_exhaustive()
    }
}

/// Attaches a repeatable default without changing the base key's identity.
pub struct SharedKeyDefault<Key, Seed> {
    /// Supplies resource identity independently of the default value.
    key: Key,
    /// Evaluates a fresh default only when the requested operation needs one.
    seed: Seed,
}

impl<Key, Seed> SharedKeyDefault<Key, Seed> {
    /// Associates a base key with a seed closure without invoking it.
    #[must_use]
    pub const fn new(key: Key, seed: Seed) -> Self {
        Self { key, seed }
    }

    /// Removes the default for require, key replacement or an overriding seed.
    ///
    /// # Panics
    /// Propagates a destructor panic from the unused seed's captures. The key is
    /// still owned locally and is dropped if that cleanup unwinds.
    #[must_use]
    pub fn into_key(self) -> Key {
        let Self { key, seed } = self;
        drop(seed);
        key
    }
}

impl<Key: SharedReaderKey, Seed: Fn() -> Key::Value> SharedKeyDefault<Key, Seed> {
    /// Evaluates the default on every direct access, independently of cache hits.
    pub fn initial_value(&self) -> Key::Value {
        (self.seed)()
    }
}

impl<Key, Seed> fmt::Debug for SharedKeyDefault<Key, Seed> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("SharedKeyDefault").finish_non_exhaustive()
    }
}

/// Keeps cache admission failures distinct from value access and provider causes.
enum Failure<Cause> {
    /// A live address has an incompatible codec, value type or concrete key type.
    Collision,
    /// A require operation found no stored value, independently of cache state.
    Absent,
    /// The namespace's metadata lock was poisoned.
    Poisoned,
    /// Access to the binding, captured value, or reload coordinator failed.
    Access(SharedAccessError),
    /// The provider's original owned load or subscription failure.
    Provider(Cause),
}

/// Preserves a cache, value-access or original typed provider failure.
pub struct SharedKeyError<Cause> {
    /// Retains the typed cause while public formatting hides provider details.
    failure: Failure<Cause>,
}

impl<Cause> SharedKeyError<Cause> {
    /// Returns whether a live address has incompatible value, key or codec identity.
    #[must_use]
    pub const fn is_collision(&self) -> bool {
        matches!(self.failure, Failure::Collision)
    }

    /// Returns whether require found no stored value.
    #[must_use]
    pub const fn is_absent(&self) -> bool {
        matches!(self.failure, Failure::Absent)
    }

    /// Returns whether the cache metadata lock was poisoned.
    #[must_use]
    pub const fn is_poisoned(&self) -> bool {
        matches!(self.failure, Failure::Poisoned)
    }

    /// Returns the access error for a binding, captured value, or reload coordinator.
    #[must_use]
    pub const fn access_error(&self) -> Option<&SharedAccessError> {
        match &self.failure {
            Failure::Access(error) => Some(error),
            _ => None,
        }
    }

    /// Recovers the original provider cause without requiring domain traits.
    #[must_use]
    pub fn into_failure(self) -> Option<Cause> {
        match self.failure {
            Failure::Provider(cause) => Some(cause),
            _ => None,
        }
    }

    /// Supplies the same redacted text to Display and quoted Debug without allocating.
    const fn message(&self) -> &'static str {
        match &self.failure {
            Failure::Collision => "shared key has an incompatible live reference",
            Failure::Absent => "required shared value is absent from storage",
            Failure::Poisoned => "shared cache metadata is poisoned",
            Failure::Access(error) => error.message(),
            Failure::Provider(_) => "shared key provider failed",
        }
    }
}

impl<Cause> fmt::Debug for SharedKeyError<Cause> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("SharedKeyError")
            .field("kind", &self.message())
            .finish_non_exhaustive()
    }
}

impl<Cause> fmt::Display for SharedKeyError<Cause> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.message())
    }
}

impl<Cause: std::error::Error + 'static> std::error::Error for SharedKeyError<Cause> {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match &self.failure {
            Failure::Access(error) => Some(error),
            Failure::Provider(cause) => Some(cause),
            _ => None,
        }
    }
}

impl<Cause> From<SharedAccessError> for SharedKeyError<Cause> {
    fn from(error: SharedAccessError) -> Self {
        Self {
            failure: Failure::Access(error),
        }
    }
}

/// Stores a provider identity for admission and later full reload checks.
#[derive(Clone, Eq, PartialEq)]
struct Compatibility {
    /// Immutable resource address, codec and configuration supplied outside locks.
    identity: SharedKeyIdentity,
}

impl Compatibility {
    /// Calls provider identity code before entering the namespace lock.
    fn for_key<Key: SharedReaderKey>(key: &Key) -> Self {
        Self {
            identity: key.identity(),
        }
    }
}

/// Admits compatible lookups without keeping their values or subscriptions alive.
struct Entry {
    /// Detects incompatible codecs after the map key established address equality.
    codec: TypeId,
    /// Retains compact codec settings; the map key already owns the resource address.
    configuration: Box<str>,
    /// Erases the value type while retaining only weak allocation identity.
    reference: Weak<dyn Any + Send + Sync>,
}

impl Entry {
    /// Compares remaining identity fields after lookup matched the resource address.
    fn matches_at_same_address(&self, other: &Compatibility) -> bool {
        self.codec == other.identity.codec
            && self.configuration.as_ref() == other.identity.configuration.as_str()
    }
}

/// Owns provider state for exactly one cached reference, not its writable cohorts.
struct KeyResource<Key: SharedReaderKey> {
    /// Retains the provider used by explicit reload after key replacement.
    key: Key,
    /// Binds later reloads to the original complete provider identity.
    compatibility: Compatibility,
    /// Rejects reload through a different namespace without retaining this cache.
    namespace: Weak<Mutex<HashMap<Box<str>, Entry>>>,
    /// Unregisters delivery when the final captured reference drops.
    _subscription: Key::Subscription,
    /// Holds only the latest request's weak identity; attempts own their tokens.
    loads: Arc<Mutex<Option<Weak<()>>>>,
}

/// Lets callers find the same live shared value by key.
///
/// Clones share the same cache. [`Self::new`] creates a separate cache.
/// Cache entries do not keep values or subscriptions alive. A reader or writable handle keeps its value alive.
/// The last reference to the value drops the subscription.
///
/// [`Self::reader`] and [`Self::shared`] reuse a live value without loading or subscribing again.
/// On a miss, each call evaluates its seed, asks the provider to load, then subscribes.
/// Concurrent misses for a compatible key can both run these steps.
/// If one call finds the other's live value, it uses that value and drops its own subscription outside the cache lock.
/// [`Self::require_reader`] and [`Self::require`] always check storage first, even on a cache hit.
///
/// The stored value can change between the load and the subscription. The cache does not replay missed updates.
/// To close this gap, the provider must replay updates, register atomically with a snapshot, or reconcile revisions.
/// A provider can also deliver a new value during subscription, before the caller receives the handle.
#[derive(Clone, Default)]
pub struct SharedKeyCache {
    /// Shares weak lookup metadata between clones, never strong value ownership.
    entries: Arc<Mutex<HashMap<Box<str>, Entry>>>,
}

impl fmt::Debug for SharedKeyCache {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("SharedKeyCache").finish_non_exhaustive()
    }
}

impl SharedKeyCache {
    /// Creates an empty independent namespace without provider work.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Returns a writable handle with its own binding to the shared value.
    ///
    /// This method uses the same load and subscription rules as [`Self::reader`].
    /// Rebinding this handle does not rebind a handle from another call for the same key.
    /// Clones of this handle do follow the new binding. See [`Shared::rebind`].
    ///
    /// # Errors
    /// Returns collision, metadata poison, or an original load/subscription failure.
    ///
    /// # Panics
    /// Propagates the same callback and destructor panics as [`Self::reader`].
    pub async fn shared<Key: SharedKey>(
        &self,
        key: Key,
        seed: impl FnOnce() -> Key::Value,
    ) -> Result<Shared<Key::Value>, SharedKeyError<Key::Error>> {
        Ok(cohort(self.reader(key, seed).await?))
    }

    /// Returns a reader for a live value or asks the provider for one.
    ///
    /// On a cache miss, the seed runs even if storage contains a value.
    /// If storage has no value, the cache uses the seed as the initial value before it subscribes.
    /// See [`SharedKeyCache`] for simultaneous misses and updates between load and subscription.
    ///
    /// # Errors
    /// Returns collision, metadata poison, or an original load/subscription failure.
    ///
    /// # Panics
    /// Propagates seed, provider and discarded value/resource destructor panics.
    /// These callbacks run without the cache lock; publication may already have
    /// occurred before cleanup panics.
    pub async fn reader<Key: SharedReaderKey>(
        &self,
        key: Key,
        seed: impl FnOnce() -> Key::Value,
    ) -> Result<SharedReader<Key::Value>, SharedKeyError<Key::Error>> {
        let compatibility = Compatibility::for_key(&key);
        if let Some(reference) = self.lookup::<Key>(&compatibility)? {
            let reader = SharedReader { reference };
            resource::<Key>(&reader)?;
            drop(compatibility);
            drop(seed);
            drop(key);
            return Ok(reader);
        }
        let seed = seed();
        let loaded = match key.load(SharedLoadContext::Initial(&seed)).await {
            Ok(loaded) => loaded,
            Err(cause) => {
                let error = provider(cause);
                drop(seed);
                drop(compatibility);
                drop(key);
                return Err(error);
            }
        };
        let value = match loaded {
            Some(value) => {
                drop(seed);
                value
            }
            None => seed,
        };
        let reference = build_reference(
            key,
            compatibility.clone(),
            Arc::downgrade(&self.entries),
            value,
            SharedSubscribeContext::Initial,
        )?;
        self.publish::<Key>(compatibility, reference)
    }

    /// Constructs with a default closure while preserving the base key identity.
    ///
    /// # Errors
    /// Returns the same failures as [`Self::shared`].
    ///
    /// # Panics
    /// Propagates the same callback and destructor panics as [`Self::reader`].
    pub async fn shared_default<Key: SharedKey, Seed: Fn() -> Key::Value>(
        &self,
        default: SharedKeyDefault<Key, Seed>,
    ) -> Result<Shared<Key::Value>, SharedKeyError<Key::Error>> {
        self.shared(default.key, default.seed).await
    }

    /// Constructs a reader without adding the default wrapper to cache identity.
    ///
    /// # Errors
    /// Returns the same failures as [`Self::reader`].
    ///
    /// # Panics
    /// Propagates the same callback and destructor panics as [`Self::reader`].
    pub async fn reader_default<Key: SharedReaderKey, Seed: Fn() -> Key::Value>(
        &self,
        default: SharedKeyDefault<Key, Seed>,
    ) -> Result<SharedReader<Key::Value>, SharedKeyError<Key::Error>> {
        self.reader(default.key, default.seed).await
    }

    /// Requires stored data before creating or reusing a writable reference.
    ///
    /// Use [`SharedKeyDefault::into_key`] to require a default key without using
    /// its seed. A live cached value may win over the newly loaded value.
    ///
    /// # Errors
    /// Returns absence, collision, poison, or original load/subscription failure.
    ///
    /// # Panics
    /// Propagates the same provider and destructor panics as [`Self::require_reader`].
    pub async fn require<Key: SharedKey>(
        &self,
        key: Key,
    ) -> Result<Shared<Key::Value>, SharedKeyError<Key::Error>> {
        Ok(cohort(self.require_reader(key).await?))
    }

    /// Requires stored data before looking up a read-only reference.
    ///
    /// # Errors
    /// Returns absence even with a live cache hit, or collision/poison/provider failure.
    ///
    /// # Panics
    /// Propagates provider and discarded value/resource destructor panics. Cleanup
    /// completes before a selected reader or original provider cause is returned.
    pub async fn require_reader<Key: SharedReaderKey>(
        &self,
        key: Key,
    ) -> Result<SharedReader<Key::Value>, SharedKeyError<Key::Error>> {
        let loaded = match key.load(SharedLoadContext::UserInitiated).await {
            Ok(loaded) => loaded,
            Err(cause) => {
                let error = provider(cause);
                drop(key);
                return Err(error);
            }
        }
        .ok_or(SharedKeyError {
            failure: Failure::Absent,
        })?;
        let compatibility = Compatibility::for_key(&key);
        if let Some(reference) = self.lookup::<Key>(&compatibility)? {
            let reader = SharedReader { reference };
            resource::<Key>(&reader)?;
            drop(compatibility);
            drop(loaded);
            drop(key);
            return Ok(reader);
        }
        let reference = build_reference(
            key,
            compatibility.clone(),
            Arc::downgrade(&self.entries),
            loaded,
            SharedSubscribeContext::UserInitiated,
        )?;
        self.publish::<Key>(compatibility, reference)
    }

    /// Reloads a captured writable reference, retaining its current value on absence.
    ///
    /// Concurrent rebinding does not retarget this operation after capture.
    /// Only the latest started reload on that reference may replace its value;
    /// completion, failure or cancellation never revives an older request.
    ///
    /// # Errors
    /// Returns incompatible key, access failure, or original provider failure.
    ///
    /// # Panics
    /// Propagates provider and displaced-value cleanup panics. Releasing the
    /// captured reference can also run a panicking destructor before return.
    pub async fn reload<Key: SharedReaderKey>(
        &self,
        shared: &Shared<Key::Value>,
        key: &Key,
    ) -> Result<(), SharedKeyError<Key::Error>> {
        let reader = shared.reader()?;
        let result = self.reload_reader(&reader, key).await;
        drop(reader);
        result
    }

    /// Reloads a read-only captured reference without granting mutation access.
    ///
    /// # Errors
    /// Returns incompatible key, value-access failure, or original provider failure.
    ///
    /// # Panics
    /// Propagates provider and displaced or rejected value destructor panics.
    pub async fn reload_reader<Key: SharedReaderKey>(
        &self,
        reader: &SharedReader<Key::Value>,
        key: &Key,
    ) -> Result<(), SharedKeyError<Key::Error>> {
        let resource = resource::<Key>(reader)?;
        if !std::ptr::eq(resource.namespace.as_ptr(), Arc::as_ptr(&self.entries))
            || resource.compatibility != Compatibility::for_key(key)
        {
            return Err(collision());
        }
        reload_reference(reader, key, &resource.loads).await
    }

    /// Rebinds to a key before reloading, seeding fresh owners from current data.
    ///
    /// `seed` runs synchronously only on a target-cache miss and supplies an
    /// owned current-value snapshot without requiring `Clone`. The new owner
    /// skips initial load and subscribes with user intent. Reload failure does
    /// not roll the binding back. Unwrap default keys with `into_key`.
    ///
    /// # Errors
    /// Returns collision, cache/value access, subscription or explicit-load failure.
    ///
    /// # Panics
    /// A seed callback panic poisons the captured source value. Provider or
    /// displaced value/resource destructor panics also propagate. The receiving
    /// handle and its clones can already refer to the replacement value.
    pub async fn load<Key: SharedKey>(
        &self,
        shared: &Shared<Key::Value>,
        key: Key,
        seed: impl FnOnce(&Key::Value) -> Key::Value,
    ) -> Result<(), SharedKeyError<Key::Error>> {
        let reader = self.replacement(&shared.reader()?, key, seed)?;
        let resource = resource::<Key>(&reader)?;
        shared.rebind(&cohort(reader.clone()))?;
        let result = reload_reference(&reader, &resource.key, &resource.loads).await;
        drop(reader);
        result
    }

    /// Replaces this reader's reference before explicitly reloading the selected key.
    ///
    /// Other reader clones retain their previously captured reference.
    ///
    /// # Errors
    /// Returns collision, cache/value access, subscription or explicit-load failure.
    ///
    /// # Panics
    /// A seed callback panic poisons the captured source value. Provider or
    /// displaced value/resource destructor panics also propagate. This reader
    /// may already be replaced and is not rolled back.
    pub async fn load_reader<Key: SharedReaderKey>(
        &self,
        reader: &mut SharedReader<Key::Value>,
        key: Key,
        seed: impl FnOnce(&Key::Value) -> Key::Value,
    ) -> Result<(), SharedKeyError<Key::Error>> {
        let replacement = self.replacement(reader, key, seed)?;
        let previous = std::mem::replace(reader, replacement);
        let resource = match resource::<Key>(reader) {
            Ok(resource) => resource,
            Err(error) => {
                drop(std::mem::replace(reader, previous));
                return Err(error);
            }
        };
        drop(previous);
        reload_reference(reader, &resource.key, &resource.loads).await
    }

    /// Clears weak lookup entries without revoking owners or touching storage.
    ///
    /// In-flight constructors may publish again after this reset.
    ///
    /// # Errors
    /// Returns metadata poison if another operation panicked while holding its lock.
    pub fn reset(&self) -> Result<(), SharedKeyError<Infallible>> {
        let previous = {
            let mut entries = self.entries.lock().map_err(|_error| poisoned())?;
            std::mem::take(&mut *entries)
        };
        drop(previous);
        Ok(())
    }

    /// Captures a replacement without rebinding the caller or performing a load.
    ///
    /// A miss snapshots the current value and subscribes with user intent. The
    /// caller validates the concrete retained resource before changing its handle.
    fn replacement<Key: SharedReaderKey>(
        &self,
        current: &SharedReader<Key::Value>,
        key: Key,
        seed: impl FnOnce(&Key::Value) -> Key::Value,
    ) -> Result<SharedReader<Key::Value>, SharedKeyError<Key::Error>> {
        let compatibility = Compatibility::for_key(&key);
        if let Some(reference) = self.lookup::<Key>(&compatibility)? {
            // The caller validates the concrete resource before committing its binding.
            let reader = SharedReader { reference };
            drop(compatibility);
            drop(seed);
            drop(key);
            return Ok(reader);
        }
        let value = current.read(seed)?;
        let reference = build_reference(
            key,
            compatibility.clone(),
            Arc::downgrade(&self.entries),
            value,
            SharedSubscribeContext::UserInitiated,
        )?;
        self.publish::<Key>(compatibility, reference)
    }

    /// Upgrades a compatible live entry, releasing the metadata lock before drops.
    #[expect(
        clippy::type_complexity,
        reason = "keeps the value type and provider failure coupled at this private boundary"
    )]
    fn lookup<Key: SharedReaderKey>(
        &self,
        compatibility: &Compatibility,
    ) -> Result<Option<Arc<SharedReference<Key::Value>>>, SharedKeyError<Key::Error>> {
        let found = {
            let entries = self.entries.lock().map_err(|_error| poisoned())?;
            entries
                .get(compatibility.identity.address.as_str())
                .map(|entry| {
                    // Compatibility contains only owned strings and type IDs, so
                    // comparing it runs no provider code. Carry the owner out
                    // even on collision: its final drop may reenter this cache.
                    (
                        entry.matches_at_same_address(compatibility),
                        entry.reference.upgrade(),
                    )
                })
        };
        match found {
            Some((compatible, Some(reference))) => {
                if !compatible {
                    return Err(collision());
                }
                reference
                    .downcast()
                    .map(Some)
                    .map_err(|_reference| collision())
            }
            _ => Ok(None),
        }
    }

    /// Selects the live winner after provider construction outside the cache lock.
    ///
    /// Losing candidates and displaced weak entries are destroyed after unlocking.
    fn publish<Key: SharedReaderKey>(
        &self,
        mut compatibility: Compatibility,
        candidate: Arc<SharedReference<Key::Value>>,
    ) -> Result<SharedReader<Key::Value>, SharedKeyError<Key::Error>> {
        let erased: Arc<dyn Any + Send + Sync> = Arc::clone(&candidate) as Arc<_>;
        let (winner, previous) = {
            let mut entries = self.entries.lock().map_err(|_error| poisoned())?;
            let winner = entries
                .get(compatibility.identity.address.as_str())
                .and_then(|entry| {
                    entry
                        .reference
                        .upgrade()
                        .map(|reference| (entry.matches_at_same_address(&compatibility), reference))
                });
            let previous = if winner.is_none() {
                entries.insert(
                    take_compact(&mut compatibility.identity.address),
                    Entry {
                        codec: compatibility.identity.codec,
                        configuration: take_compact(&mut compatibility.identity.configuration),
                        reference: Arc::downgrade(&erased),
                    },
                )
            } else {
                None
            };
            (winner, previous)
        };
        drop(previous);
        drop(erased);
        if let Some((compatible, winner)) = winner {
            if !compatible {
                return Err(collision());
            }
            let reader = SharedReader {
                reference: winner.downcast().map_err(|_reference| collision())?,
            };
            resource::<Key>(&reader)?;
            drop(candidate);
            return Ok(reader);
        }
        Ok(SharedReader {
            reference: candidate,
        })
    }
}

/// Moves compact text or copies it without releasing its excess capacity.
fn take_compact(text: &mut String) -> Box<str> {
    if text.len() == text.capacity() {
        std::mem::take(text).into_boxed_str()
    } else {
        // The caller releases the original buffer after the cache lock.
        Box::from(text.as_str())
    }
}

/// Creates an independent rebinding slot over an already captured reference.
fn cohort<Value>(reader: SharedReader<Value>) -> Shared<Value> {
    Shared {
        cohort: Arc::new(Mutex::new(reader)),
    }
}

/// Establishes weak delivery before subscribing, then retains the provider guard.
///
/// Synchronous subscription delivery may replace the seed. The one-time slot
/// keeps the provider's type recoverable without locking during later lookups.
fn build_reference<Key: SharedReaderKey>(
    key: Key,
    compatibility: Compatibility,
    namespace: Weak<Mutex<HashMap<Box<str>, Entry>>>,
    value: Key::Value,
    context: SharedSubscribeContext,
) -> Result<Arc<SharedReference<Key::Value>>, SharedKeyError<Key::Error>> {
    let reference = Arc::new(SharedReference::new(value));
    // Establish delivery arbitration before subscribe can synchronously yield.
    let loads = Arc::new(Mutex::new(None));
    let subscription = match key.subscribe(
        context,
        SharedSubscriber {
            reference: Arc::downgrade(&reference),
            loads: Arc::downgrade(&loads),
        },
    ) {
        Ok(subscription) => subscription,
        Err(cause) => {
            let error = provider(cause);
            drop(loads);
            drop(reference);
            drop(namespace);
            drop(compatibility);
            drop(key);
            return Err(error);
        }
    };
    // Only construction can install the resource. The supplied subscriber holds weak references.
    let installed = reference.retained.set(Box::new(KeyResource {
        key,
        compatibility,
        namespace,
        _subscription: subscription,
        loads,
    }));
    assert!(
        installed.is_ok(),
        "a new shared reference has no retained resource"
    );
    Ok(reference)
}

/// Checks the concrete provider type as well as the reference's already typed value.
fn resource<Key: SharedReaderKey>(
    reader: &SharedReader<Key::Value>,
) -> Result<&KeyResource<Key>, SharedKeyError<Key::Error>> {
    reader
        .reference
        .retained
        .get()
        .and_then(|resource| resource.downcast_ref::<KeyResource<Key>>())
        .ok_or_else(collision)
}

/// Starts one reload and commits only if no later load or delivery superseded it.
async fn reload_reference<Key: SharedReaderKey>(
    reader: &SharedReader<Key::Value>,
    key: &Key,
    loads: &Mutex<Option<Weak<()>>>,
) -> Result<(), SharedKeyError<Key::Error>> {
    let attempt = ReferenceLoadAttempt::begin(&reader.reference, loads)?;
    let loaded = key
        .load(SharedLoadContext::UserInitiated)
        .await
        .map_err(provider)?;
    attempt.commit(loaded)?;
    Ok(())
}

/// Owns one non-reusable request token and retires it on cancellation or failure.
struct ReferenceLoadAttempt<'a, Value> {
    /// Borrows the captured destination for the complete load attempt.
    reference: &'a SharedReference<Value>,
    /// Serialises token replacement with value commit and producer delivery.
    loads: &'a Mutex<Option<Weak<()>>>,
    /// Keeps this request's allocation identity unique while the attempt exists.
    identity: Arc<()>,
    /// Skips cancellation cleanup once commit has consumed this request's authority.
    retired: bool,
}

impl<'a, Value> ReferenceLoadAttempt<'a, Value> {
    /// Supersedes earlier attempts before starting provider work.
    fn begin(
        reference: &'a SharedReference<Value>,
        loads: &'a Mutex<Option<Weak<()>>>,
    ) -> Result<Self, SharedAccessError> {
        let identity = Arc::new(());
        let previous = {
            let mut latest = loads.lock().map_err(|_error| load_poisoned())?;
            latest.replace(Arc::downgrade(&identity))
        };
        drop(previous);
        Ok(Self {
            reference,
            loads,
            identity,
            retired: false,
        })
    }

    /// Compares request identity without reviving a completed or cancelled attempt.
    fn is_latest(&self, latest: Option<&Weak<()>>) -> bool {
        // Both owners keep their allocation identities unique; comparison needs
        // no temporary Weak increment/decrement or upgrade of a retired request.
        latest.is_some_and(|latest| std::ptr::eq(latest.as_ptr(), Arc::as_ptr(&self.identity)))
    }

    /// Applies only the latest result, dropping displaced or rejected values unlocked.
    ///
    /// Absence retires the latest request without replacing its current value.
    fn commit(mut self, value: Option<Value>) -> Result<bool, SharedAccessError> {
        let mut value = value;
        let (committed, displaced, previous) = {
            let mut latest = self.loads.lock().map_err(|_error| load_poisoned())?;
            if self.is_latest(latest.as_ref()) {
                // Validate and replace under one coordinator guard. Never
                // block on value access or drop user values under either lock.
                let displaced = if value.is_some() {
                    let mut current = try_lock(&self.reference.value)?;
                    value
                        .take()
                        .map(|value| std::mem::replace(&mut *current, value))
                } else {
                    None
                };
                (true, displaced, latest.take())
            } else {
                (false, None, None)
            }
        };
        self.retired = true;
        drop(previous);
        drop(displaced);
        drop(value);
        Ok(committed)
    }
}

impl<Value> Drop for ReferenceLoadAttempt<'_, Value> {
    fn drop(&mut self) {
        if self.retired {
            return;
        }
        // Drop cannot report poison and must not introduce a second panic.
        // A poisoned coordinator remains poisoned for subsequent operations.
        let previous = if let Ok(mut latest) = self.loads.lock() {
            if self.is_latest(latest.as_ref()) {
                latest.take()
            } else {
                None
            }
        } else {
            None
        };
        drop(previous);
    }
}

/// Classifies reload-coordinator poison as captured-reference access failure.
fn load_poisoned() -> SharedAccessError {
    SharedAccessError {
        kind: super::AccessKind::Poisoned,
    }
}

/// Preserves a provider cause without formatting or cloning it.
fn provider<Cause>(cause: Cause) -> SharedKeyError<Cause> {
    SharedKeyError {
        failure: Failure::Provider(cause),
    }
}

/// Reports incompatible live identity without exposing resource details.
fn collision<Cause>() -> SharedKeyError<Cause> {
    SharedKeyError {
        failure: Failure::Collision,
    }
}

/// Distinguishes namespace metadata poison from captured-reference access poison.
fn poisoned<Cause>() -> SharedKeyError<Cause> {
    SharedKeyError {
        failure: Failure::Poisoned,
    }
}

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

    /// Checks that the result owns each non-empty, exact-sized buffer.
    #[test]
    fn take_compact_transfers_exact_capacity_buffers() {
        for expected in ["", "shared-profile"] {
            let mut text = Box::<str>::from(expected).into_string();
            let pointer = text.as_ptr();
            assert_eq!(text.capacity(), text.len());

            let compact = take_compact(&mut text);

            assert_eq!(compact.as_ref(), expected);
            if !expected.is_empty() {
                assert_eq!(compact.as_ptr(), pointer);
            }
            assert_eq!(text, "");
            assert_eq!(text.capacity(), 0);
        }
    }

    /// Checks that copies leave oversized buffers with the caller.
    #[test]
    fn take_compact_preserves_buffers_with_spare_capacity() {
        for expected in ["", "shared-profile"] {
            let mut text = String::with_capacity(expected.len() + 16);
            text.push_str(expected);
            let pointer = text.as_ptr();
            let capacity = text.capacity();
            assert!(capacity > text.len());

            let compact = take_compact(&mut text);

            assert_eq!(compact.as_ref(), expected);
            assert_eq!(text, expected);
            assert_eq!(text.as_ptr(), pointer);
            assert_eq!(text.capacity(), capacity);
            if !expected.is_empty() {
                assert_ne!(compact.as_ptr(), pointer);
            }
        }
    }

    // Diagnostic formatting must neither require Debug on values nor disclose them.
    #[test]
    fn diagnostics_redact_resource_identity_and_non_debug_values() {
        struct Secret(&'static str);

        let identity = SharedKeyIdentity::new::<()>("private-address", "private-configuration");
        let reference = Arc::new(SharedReference::new(Secret("private-value")));
        let loads = Arc::new(Mutex::new(None));
        let subscriber = SharedSubscriber {
            reference: Arc::downgrade(&reference),
            loads: Arc::downgrade(&loads),
        };
        let publication = subscriber.prepare_publication().unwrap();
        let value = reference.value.lock().unwrap();
        let initial = format!("{:?}", SharedLoadContext::Initial(&*value));
        let explicit = format!("{:?}", SharedLoadContext::<Secret>::UserInitiated);
        assert_ne!(initial, explicit);
        for diagnostic in [
            format!("{identity:?}"),
            format!("{subscriber:?}"),
            format!("{publication:?}"),
            format!("{:?}", SharedKeyCache::new()),
            initial,
            explicit,
        ] {
            for secret in ["private-address", "private-configuration", value.0] {
                assert!(!diagnostic.contains(secret));
            }
        }
    }

    // Public diagnostics redact provider details while the typed error chain preserves them.
    #[test]
    fn provider_error_source_preserves_the_cause_without_disclosing_it() {
        let error = provider(std::io::Error::new(
            std::io::ErrorKind::PermissionDenied,
            "private-provider-path",
        ));
        assert!(!error.is_absent());
        assert!(!error.is_collision());
        assert!(!error.is_poisoned());
        assert!(error.access_error().is_none());
        assert!(!format!("{error}: {error:?}").contains("private-provider-path"));
        let source = std::error::Error::source(&error)
            .unwrap()
            .downcast_ref::<std::io::Error>()
            .unwrap();
        assert_eq!(source.kind(), std::io::ErrorKind::PermissionDenied);
        assert_eq!(source.to_string(), "private-provider-path");
        let recovered = error.into_failure().unwrap();
        assert_eq!(recovered.kind(), std::io::ErrorKind::PermissionDenied);
        assert_eq!(recovered.to_string(), "private-provider-path");
    }

    // Poison must reject all metadata operations without revoking captured owners.
    #[test]
    fn poisoned_metadata_rejects_lookup_publication_and_reset_without_revoking_owners() {
        let cache = SharedKeyCache::new();
        let seeds = std::cell::Cell::new(0);
        let seed = || {
            seeds.set(seeds.get() + 1);
            7
        };
        let owner = futures_executor::block_on(cache.reader(LayoutKey, seed)).unwrap();
        let compatibility = Compatibility::for_key(&LayoutKey);
        let candidate = build_reference(
            LayoutKey,
            compatibility.clone(),
            Arc::downgrade(&cache.entries),
            11,
            SharedSubscribeContext::UserInitiated,
        )
        .unwrap();
        let provisional = Arc::downgrade(&candidate);
        let panic = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            let _guard = cache.entries.lock().unwrap();
            panic!("metadata interrupted");
        }));
        assert!(panic.is_err());
        let errors = [
            futures_executor::block_on(cache.reader(LayoutKey, seed)).unwrap_err(),
            cache
                .publish::<LayoutKey>(compatibility, candidate)
                .unwrap_err(),
            cache.reset().unwrap_err(),
        ];
        for error in errors {
            assert!(error.is_poisoned());
            assert!(!error.is_collision());
            assert!(!error.is_absent());
            assert!(error.access_error().is_none());
            assert!(std::error::Error::source(&error).is_none());
            assert!(error.to_string().contains("metadata is poisoned"));
            assert!(error.into_failure().is_none());
        }
        assert_eq!(seeds.get(), 1);
        assert!(provisional.upgrade().is_none());
        assert_eq!(owner.read(|value| *value).unwrap(), 7);
    }

    // Internal fault injection, not a publicly constructible cache state.
    #[test]
    fn mismatched_erased_entry_rejects_reader_without_seed_or_owner_leak() {
        let cache = SharedKeyCache::new();
        let compatibility = Compatibility::for_key(&LayoutKey);
        let owner = Arc::new(SharedReference::new("private-wrong-value"));
        let erased: Arc<dyn Any + Send + Sync> = Arc::clone(&owner) as Arc<_>;
        cache.entries.lock().unwrap().insert(
            compatibility.identity.address.clone().into_boxed_str(),
            Entry {
                codec: compatibility.identity.codec,
                configuration: compatibility
                    .identity
                    .configuration
                    .clone()
                    .into_boxed_str(),
                reference: Arc::downgrade(&erased),
            },
        );
        drop(erased);

        let error = futures_executor::block_on(cache.reader(LayoutKey, || {
            panic!("a mismatched live reference must not fall back to its seed")
        }))
        .unwrap_err();
        assert!(error.is_collision());
        assert_eq!(
            error.to_string(),
            "shared key has an incompatible live reference"
        );
        assert!(!format!("{error:?}").contains("private-wrong-value"));
        assert!(!error.is_poisoned());
        assert_eq!(Arc::strong_count(&owner), 1);
        assert_eq!(*owner.value.lock().unwrap(), "private-wrong-value");
        drop(cache);
        assert_eq!(Arc::strong_count(&owner), 1);
    }

    // A forged compatible identity must not turn a failed downcast into publication.
    #[test]
    fn mismatched_erased_winner_rejects_publication_and_drops_candidate_outside_lock() {
        use std::sync::atomic::{AtomicUsize, Ordering};

        struct CandidateDrop(SharedKeyCache, Arc<AtomicUsize>);
        impl Drop for CandidateDrop {
            fn drop(&mut self) {
                assert!(
                    self.0.entries.try_lock().is_ok(),
                    "candidate drop holds metadata lock"
                );
                self.1.fetch_add(1, Ordering::SeqCst);
            }
        }

        let cache = SharedKeyCache::new();
        let compatibility = Compatibility::for_key(&LayoutKey);
        let owner = Arc::new(SharedReference::new("private-wrong-value"));
        let erased: Arc<dyn Any + Send + Sync> = Arc::clone(&owner) as Arc<_>;
        let retained = Arc::downgrade(&erased);
        cache.entries.lock().unwrap().insert(
            compatibility.identity.address.clone().into_boxed_str(),
            Entry {
                codec: compatibility.identity.codec,
                configuration: compatibility
                    .identity
                    .configuration
                    .clone()
                    .into_boxed_str(),
                reference: Weak::clone(&retained),
            },
        );
        drop(erased);
        let drops = Arc::new(AtomicUsize::new(0));
        let candidate = Arc::new(SharedReference::new(11_usize));
        candidate
            .retained
            .set(Box::new(CandidateDrop(cache.clone(), Arc::clone(&drops))))
            .unwrap_or_else(|_| panic!("fresh candidate has no retained resource"));
        let provisional = Arc::downgrade(&candidate);

        let error = cache
            .publish::<LayoutKey>(compatibility.clone(), candidate)
            .unwrap_err();
        assert!(error.is_collision());
        assert_eq!(
            error.to_string(),
            "shared key has an incompatible live reference"
        );
        assert!(!format!("{error:?}").contains("private-wrong-value"));
        assert_eq!(drops.load(Ordering::SeqCst), 1);
        assert!(provisional.upgrade().is_none());
        assert_eq!(Arc::strong_count(&owner), 1);
        let entries = cache.entries.lock().unwrap();
        assert_eq!(entries.len(), 1);
        assert!(Weak::ptr_eq(
            &entries[compatibility.identity.address.as_str()].reference,
            &retained
        ));
        drop(entries);
        assert_eq!(*owner.value.lock().unwrap(), "private-wrong-value");
        drop(cache);
        assert_eq!(drops.load(Ordering::SeqCst), 1);
        assert_eq!(Arc::strong_count(&drops), 1);
    }

    // A poisoned coordinator cannot accept a new load, commit or producer value.
    #[test]
    fn poisoned_reload_coordinator_preserves_values_and_does_not_panic_during_retirement() {
        let reference = Arc::new(SharedReference::new(7));
        let loads = Arc::new(Mutex::new(None));
        let subscriber = SharedSubscriber {
            reference: Arc::downgrade(&reference),
            loads: Arc::downgrade(&loads),
        };
        let publication = subscriber.prepare_publication().unwrap();
        let attempt = ReferenceLoadAttempt::begin(&reference, &loads).unwrap();
        let panic = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            let _guard = loads.lock().unwrap();
            panic!("reload coordination interrupted");
        }));
        assert!(panic.is_err());
        assert!(attempt.commit(Some(11)).unwrap_err().is_poisoned());
        let error = ReferenceLoadAttempt::begin(&reference, &loads)
            .err()
            .unwrap();
        assert!(error.is_poisoned());
        let mut next = 13;
        assert!(
            publication
                .try_replace(&mut next)
                .unwrap_err()
                .is_poisoned()
        );
        assert_eq!(next, 13);
        assert_eq!(*reference.value.lock().unwrap(), 7);
        assert!(loads.is_poisoned());
    }

    // Coordinator poison must reach callers before provider I/O, without leaking owners.
    #[test]
    fn reload_propagates_coordinator_poison_before_invoking_provider() {
        use std::sync::atomic::{AtomicUsize, Ordering};

        #[derive(Clone)]
        struct Key {
            loads: Arc<AtomicUsize>,
            retirements: Arc<AtomicUsize>,
        }
        struct Subscription(Arc<AtomicUsize>);

        impl Drop for Subscription {
            fn drop(&mut self) {
                self.0.fetch_add(1, Ordering::SeqCst);
            }
        }

        impl SharedReaderKey for Key {
            type Value = usize;
            type Error = Infallible;
            type Subscription = Subscription;

            fn identity(&self) -> SharedKeyIdentity {
                SharedKeyIdentity::new::<Self>("poisoned-reload", "")
            }

            fn load(
                &self,
                _: SharedLoadContext<'_, usize>,
            ) -> impl Future<Output = Result<Option<usize>, Infallible>> + Send {
                self.loads.fetch_add(1, Ordering::SeqCst);
                std::future::ready(Ok(None))
            }

            fn subscribe(
                &self,
                _: SharedSubscribeContext,
                _: SharedSubscriber<usize>,
            ) -> Result<Subscription, Infallible> {
                Ok(Subscription(Arc::clone(&self.retirements)))
            }
        }

        let key = Key {
            loads: Arc::new(AtomicUsize::new(0)),
            retirements: Arc::new(AtomicUsize::new(0)),
        };
        let cache = SharedKeyCache::new();
        let reader = futures_executor::block_on(cache.reader(key.clone(), || 7)).unwrap();
        let owner = Arc::downgrade(&reader.reference);
        let loads = Arc::clone(&resource::<Key>(&reader).unwrap().loads);
        assert_eq!(key.loads.load(Ordering::SeqCst), 1);
        let panic = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            let _guard = loads.lock().unwrap();
            panic!("reload coordination interrupted");
        }));
        assert!(panic.is_err());

        let error = futures_executor::block_on(cache.reload_reader(&reader, &key)).unwrap_err();
        assert!(error.access_error().unwrap().is_poisoned());
        assert!(!error.is_poisoned(), "not a metadata-lock failure");
        assert!(!error.is_collision());
        assert!(
            std::error::Error::source(&error)
                .unwrap()
                .downcast_ref::<SharedAccessError>()
                .unwrap()
                .is_poisoned()
        );
        assert_eq!(key.loads.load(Ordering::SeqCst), 1);
        assert_eq!(reader.read(|value| *value).unwrap(), 7);
        assert!(loads.is_poisoned());
        assert_eq!(key.retirements.load(Ordering::SeqCst), 0);
        drop(reader);
        assert!(owner.upgrade().is_none());
        assert_eq!(key.retirements.load(Ordering::SeqCst), 1);
    }

    // Capture contention must fail before a reload reaches the provider.
    #[test]
    fn reload_rejects_a_busy_cohort_without_changing_its_capture() {
        use std::sync::atomic::{AtomicUsize, Ordering};

        #[derive(Clone)]
        struct CountingKey(Arc<AtomicUsize>);

        impl SharedReaderKey for CountingKey {
            type Value = usize;
            type Error = Infallible;
            type Subscription = ();

            fn identity(&self) -> SharedKeyIdentity {
                SharedKeyIdentity::new::<Self>("busy-cohort", "")
            }

            fn load(
                &self,
                _: SharedLoadContext<'_, usize>,
            ) -> impl Future<Output = Result<Option<usize>, Infallible>> + Send {
                self.0.fetch_add(1, Ordering::SeqCst);
                std::future::ready(Ok(None))
            }

            fn subscribe(
                &self,
                _: SharedSubscribeContext,
                _: SharedSubscriber<usize>,
            ) -> Result<(), Infallible> {
                Ok(())
            }
        }

        let key = CountingKey(Arc::new(AtomicUsize::new(0)));
        let cache = SharedKeyCache::new();
        let reader = futures_executor::block_on(cache.reader(key.clone(), || 7)).unwrap();
        assert_eq!(key.0.load(Ordering::SeqCst), 1);
        let shared = cohort(reader.clone());
        let guard = shared.cohort.lock().unwrap();
        let error = futures_executor::block_on(cache.reload(&shared, &key)).unwrap_err();
        assert!(error.access_error().unwrap().is_busy());
        assert_eq!(key.0.load(Ordering::SeqCst), 1);
        assert_eq!(reader.read(|value| *value).unwrap(), 7);
        drop(guard);
        futures_executor::block_on(cache.reload(&shared, &key)).unwrap();
        assert_eq!(key.0.load(Ordering::SeqCst), 2);
        assert_eq!(shared.read(|value| *value).unwrap(), 7);
    }

    // Private cohort guards stop capture or rebind without fabricating cache state.
    #[test]
    fn load_contention_retires_provisional_subscription_before_retry() {
        #[derive(Clone)]
        struct Key(Arc<Mutex<Vec<&'static str>>>);
        struct Subscription(Arc<Mutex<Vec<&'static str>>>);
        impl Drop for Subscription {
            fn drop(&mut self) {
                self.0.lock().unwrap().push("retire");
            }
        }
        impl SharedReaderKey for Key {
            type Value = String;
            type Error = Infallible;
            type Subscription = Subscription;

            fn identity(&self) -> SharedKeyIdentity {
                SharedKeyIdentity::new::<Self>("contended-load", "")
            }
            fn load(
                &self,
                context: SharedLoadContext<'_, String>,
            ) -> impl Future<Output = Result<Option<String>, Infallible>> + Send {
                assert!(matches!(context, SharedLoadContext::UserInitiated));
                self.0.lock().unwrap().push("reload");
                std::future::ready(Ok(None))
            }
            fn subscribe(
                &self,
                context: SharedSubscribeContext,
                _: SharedSubscriber<String>,
            ) -> Result<Subscription, Infallible> {
                assert_eq!(context, SharedSubscribeContext::UserInitiated);
                self.0.lock().unwrap().push("subscribe");
                Ok(Subscription(Arc::clone(&self.0)))
            }
        }
        impl SharedKey for Key {
            fn save(&self, _: &String) -> impl Future<Output = Result<(), Infallible>> + Send {
                self.0.lock().unwrap().push("save");
                std::future::ready(Ok(()))
            }
        }

        let cache = SharedKeyCache::new();
        let key = Key(Arc::new(Mutex::new(Vec::new())));
        let shared = Shared::new(String::from("original"));
        let original = shared.reader().unwrap();
        let guard = shared.cohort.lock().unwrap();
        let error = futures_executor::block_on(cache.load(&shared, key.clone(), |_| {
            panic!("capture contention must not seed")
        }))
        .unwrap_err();
        assert!(error.access_error().unwrap().is_busy());
        assert!(error.into_failure().is_none());
        assert!(key.0.lock().unwrap().is_empty());
        drop(guard);

        let mut retained_guard = None;
        let error = futures_executor::block_on(cache.load(&shared, key.clone(), |value| {
            assert_eq!(value, "original");
            retained_guard = Some(shared.cohort.lock().unwrap());
            String::from("provisional")
        }))
        .unwrap_err();
        assert!(error.access_error().unwrap().is_busy());
        assert!(error.into_failure().is_none());
        assert_eq!(*key.0.lock().unwrap(), ["subscribe", "retire"]);
        drop(retained_guard);
        assert!(shared.read(|value| value == "original").unwrap());
        assert!(original.read(|value| value == "original").unwrap());

        futures_executor::block_on(cache.load(&shared, key.clone(), |value| {
            assert_eq!(value, "original");
            String::from("replacement")
        }))
        .unwrap();
        assert_eq!(
            *key.0.lock().unwrap(),
            ["subscribe", "retire", "subscribe", "reload"]
        );
        assert!(shared.read(|value| value == "replacement").unwrap());
        assert!(original.read(|value| value == "original").unwrap());
        drop(shared);
        assert_eq!(
            *key.0.lock().unwrap(),
            ["subscribe", "retire", "subscribe", "reload", "retire"]
        );
    }

    #[test]
    fn failed_subscription_orphan_cannot_prepare_without_its_coordinator() {
        struct Value(u8, Arc<Mutex<Vec<u8>>>);
        impl Drop for Value {
            fn drop(&mut self) {
                self.1.lock().unwrap().push(self.0);
            }
        }
        struct Captured {
            subscriber: SharedSubscriber<Value>,
            publication: SharedPublication<Value>,
        }
        struct FailingSubscription(Arc<Mutex<Option<Captured>>>);
        impl SharedReaderKey for FailingSubscription {
            type Value = Value;
            type Error = &'static str;
            type Subscription = ();

            fn identity(&self) -> SharedKeyIdentity {
                SharedKeyIdentity::new::<Self>("orphan", "")
            }

            fn load(
                &self,
                _: SharedLoadContext<'_, Value>,
            ) -> impl Future<Output = Result<Option<Value>, &'static str>> + Send {
                std::future::ready(Ok(None))
            }

            fn subscribe(
                &self,
                context: SharedSubscribeContext,
                subscriber: SharedSubscriber<Value>,
            ) -> Result<(), &'static str> {
                assert!(matches!(context, SharedSubscribeContext::Initial));
                let publication = subscriber.prepare_publication().unwrap();
                assert!(
                    self.0
                        .lock()
                        .unwrap()
                        .replace(Captured {
                            subscriber,
                            publication,
                        })
                        .is_none()
                );
                Err("subscription failed")
            }
        }

        let cache = SharedKeyCache::new();
        let captured = Arc::new(Mutex::new(None));
        let drops = Arc::new(Mutex::new(Vec::new()));
        let error = futures_executor::block_on(
            cache.reader(FailingSubscription(Arc::clone(&captured)), || {
                Value(1, Arc::clone(&drops))
            }),
        )
        .unwrap_err();
        assert_eq!(error.into_failure(), Some("subscription failed"));
        assert!(cache.entries.lock().unwrap().is_empty());
        assert!(drops.lock().unwrap().is_empty());
        let Captured {
            subscriber,
            publication,
        } = captured.lock().unwrap().take().unwrap();

        // Split a real provisional owner only at this private protocol boundary.
        // This is not a public scheduling proof or a fabricated weak identity.
        let SharedPublication { reference, loads } = publication;
        assert!(reference.retained.get().is_none());
        assert_eq!(Arc::strong_count(&reference), 1);
        assert_eq!(Arc::strong_count(&loads), 1);
        drop(loads);
        assert!(subscriber.loads.upgrade().is_none());
        assert_eq!(subscriber.reference.strong_count(), 1);

        assert!(subscriber.prepare_publication().is_none());
        assert_eq!(Arc::strong_count(&reference), 1);
        assert_eq!(reference.value.lock().unwrap().0, 1);
        assert!(drops.lock().unwrap().is_empty());
        assert!(
            !subscriber
                .yield_value(Value(2, Arc::clone(&drops)))
                .unwrap()
        );
        assert_eq!(*drops.lock().unwrap(), [2]);
        assert_eq!(reference.value.lock().unwrap().0, 1);
        assert_eq!(Arc::strong_count(&reference), 1);
        drop(reference);
        assert_eq!(*drops.lock().unwrap(), [2, 1]);
        assert!(subscriber.reference.upgrade().is_none());
        assert!(subscriber.prepare_publication().is_none());
        drop(subscriber);
        drop(cache);
        assert_eq!(*drops.lock().unwrap(), [2, 1]);
        assert_eq!(Arc::strong_count(&drops), 1);
    }

    #[test]
    fn subscriber_swap_retains_displaced_value_until_external_fence_is_released() {
        struct Reentrant(Arc<Mutex<bool>>, Arc<std::sync::atomic::AtomicUsize>);
        impl Drop for Reentrant {
            fn drop(&mut self) {
                *self
                    .0
                    .try_lock()
                    .expect("destructor can reenter cancellation") = false;
                self.1.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
            }
        }
        let control = Arc::new(Mutex::new(true));
        let drops = Arc::new(std::sync::atomic::AtomicUsize::new(0));
        let reference = Arc::new(SharedReference::new(Reentrant(
            Arc::clone(&control),
            Arc::clone(&drops),
        )));
        let loads = Arc::new(Mutex::new(None));
        let subscriber = SharedSubscriber {
            reference: Arc::downgrade(&reference),
            loads: Arc::downgrade(&loads),
        };
        let mut next = Reentrant(Arc::clone(&control), Arc::clone(&drops));
        let publication = subscriber.prepare_publication().unwrap();
        drop(reference);
        let guard = control.lock().unwrap();
        assert!(publication.try_replace(&mut next).unwrap());
        drop(guard);
        drop(next);
        assert_eq!(drops.load(std::sync::atomic::Ordering::SeqCst), 1);
        drop(publication);
        assert_eq!(drops.load(std::sync::atomic::Ordering::SeqCst), 2);
        assert!(!*control.lock().unwrap());
        assert!(subscriber.prepare_publication().is_none());
    }

    #[test]
    fn prepared_publication_and_cancellation_have_one_final_commit_order() {
        let reference = Arc::new(SharedReference::new(7));
        let loads = Arc::new(Mutex::new(None));
        let subscriber = SharedSubscriber {
            reference: Arc::downgrade(&reference),
            loads: Arc::downgrade(&loads),
        };
        let publication = subscriber.prepare_publication().unwrap();
        let control = Arc::new(Mutex::new(true));
        let publishing = Arc::clone(&control);
        let cancelling = Arc::clone(&control);
        let (checked, checked_rx) = std::sync::mpsc::channel();
        let (resume, resume_rx) = std::sync::mpsc::channel();
        let (attempted, attempted_rx) = std::sync::mpsc::channel();
        let (cancelled, cancelled_rx) = std::sync::mpsc::channel();
        let worker = std::thread::spawn(move || {
            let mut next = 8;
            let fence = publishing.lock().unwrap();
            assert!(*fence);
            checked.send(()).unwrap();
            resume_rx.recv().unwrap(); // controlled pause immediately before swap
            assert!(publication.try_replace(&mut next).unwrap());
            drop(fence);
            assert_eq!(next, 7);
        });
        checked_rx.recv().unwrap();
        let cancellation_worker = std::thread::spawn(move || {
            attempted.send(()).unwrap();
            *cancelling.lock().unwrap() = false;
            cancelled.send(()).unwrap();
        });
        attempted_rx.recv().unwrap();
        assert_eq!(*reference.value.lock().unwrap(), 7);
        assert!(matches!(
            cancelled_rx.try_recv(),
            Err(std::sync::mpsc::TryRecvError::Empty)
        ));
        resume.send(()).unwrap();
        worker.join().unwrap();
        cancellation_worker.join().unwrap();
        cancelled_rx.recv().unwrap();
        assert_eq!(*reference.value.lock().unwrap(), 8);
        let publication = subscriber.prepare_publication().unwrap();
        let mut next = 99;
        {
            let fence = control.lock().unwrap();
            if *fence {
                publication.try_replace(&mut next).unwrap();
            }
        }
        assert_eq!(next, 99);
        assert_eq!(*reference.value.lock().unwrap(), 8);
    }

    #[test]
    fn obsolete_attempts_cannot_clear_the_latest_loading_token() {
        let reference = SharedReference::new(1);
        let loads = Mutex::new(None);
        let old = ReferenceLoadAttempt::begin(&reference, &loads).unwrap();
        let latest = ReferenceLoadAttempt::begin(&reference, &loads).unwrap();
        assert!(!old.commit(Some(10)).unwrap());
        assert!(latest.is_latest(loads.lock().unwrap().as_ref()));
        assert!(latest.commit(Some(20)).unwrap());
        assert!(loads.lock().unwrap().is_none());
        assert_eq!(*reference.value.lock().unwrap(), 20);

        let old = ReferenceLoadAttempt::begin(&reference, &loads).unwrap();
        let latest = ReferenceLoadAttempt::begin(&reference, &loads).unwrap();
        drop(old);
        assert!(latest.is_latest(loads.lock().unwrap().as_ref()));
        drop(latest);
        assert!(loads.lock().unwrap().is_none());
    }

    #[test]
    fn latest_busy_commit_retires_without_replacing_or_poisoning() {
        let reference = SharedReference::new(1);
        let loads = Mutex::new(None);
        let attempt = ReferenceLoadAttempt::begin(&reference, &loads).unwrap();
        let current = reference.value.lock().unwrap();
        assert!(attempt.commit(Some(2)).unwrap_err().is_busy());
        assert!(loads.lock().unwrap().is_none());
        assert_eq!(*current, 1);
        drop(current);
        assert!(
            ReferenceLoadAttempt::begin(&reference, &loads)
                .unwrap()
                .commit(Some(3))
                .unwrap()
        );
    }

    struct LayoutKey;

    impl SharedReaderKey for LayoutKey {
        type Value = usize;
        type Error = Infallible;
        type Subscription = ();

        fn identity(&self) -> SharedKeyIdentity {
            SharedKeyIdentity::new::<()>("layout", "")
        }

        fn load(
            &self,
            _: SharedLoadContext<'_, usize>,
        ) -> impl Future<Output = Result<Option<usize>, Infallible>> + Send {
            std::future::ready(Ok(None))
        }

        fn subscribe(
            &self,
            _: SharedSubscribeContext,
            _: SharedSubscriber<usize>,
        ) -> Result<(), Infallible> {
            Ok(())
        }
    }

    #[test]
    fn reports_retained_reference_layout() {
        // Adding keyed metadata to public handles would increase every capture.
        assert_eq!(size_of::<Shared<usize>>(), size_of::<Arc<()>>());
        assert_eq!(size_of::<SharedReader<usize>>(), size_of::<Arc<()>>());
        eprintln!(
            "Shared<usize>={} SharedReader<usize>={} old-value-mutex={} retained-reference={} keyed-resource={} coordinator={} attempt={} strong-token={} weak-token={} subscriber={}",
            size_of::<Shared<usize>>(),
            size_of::<SharedReader<usize>>(),
            size_of::<Mutex<usize>>(),
            size_of::<SharedReference<usize>>(),
            size_of::<KeyResource<LayoutKey>>(),
            size_of::<Mutex<Option<Weak<()>>>>(),
            size_of::<ReferenceLoadAttempt<'_, usize>>(),
            size_of::<Arc<()>>(),
            size_of::<Weak<()>>(),
            size_of::<SharedSubscriber<usize>>(),
        );
    }
}