dcontext 0.9.0

Distributed context propagation for Rust — scoped, type-safe, serializable
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
use serde::{Deserialize, Serialize};

#[cfg(feature = "base64")]
use base64::Engine as _;

use crate::*;
// Re-import from the crate root
use crate::wire::test_helpers::{make_wire_bytes, make_wire_bytes_v};
use crate::ContextError;
use crate::ContextSnapshot;
use crate::ScopeGuard;
use std::future::Future;

// ── Test types ─────────────────────────────────────────────────

#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)]
struct RequestId(String);

#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)]
struct UserId(u64);

// ── Helpers ────────────────────────────────────────────────────

/// Each test needs isolated registration. Since the global registry is shared,
/// we use unique key names per test to avoid conflicts.
fn unique_key(prefix: &str, suffix: &str) -> &'static str {
    // Leak a unique string for each test key — acceptable in tests.
    let s = format!("{}_{}", prefix, suffix);
    Box::leak(s.into_boxed_str())
}

fn with_snapshot<F: Future>(snap: ContextSnapshot, fut: F) -> WithContext<F> {
    fut.with(snap.into())
}

async fn async_scope<F: Future>(name: &str, fut: F) -> F::Output {
    let _scope = push_scope(name);
    fut.await
}

fn enter_scope() -> ScopeGuard {
    crate::registry::with_global_registry(|registry| {
        crate::store::try_apply(|store| ScopeGuard::new(store.push_scope(registry, None)))
            .unwrap_or_else(ScopeGuard::noop)
    })
}

fn enter_named_scope(name: impl Into<String>) -> ScopeGuard {
    let name = name.into();
    push_scope(&name)
}

fn set_context<T>(key: &'static str, value: T)
where
    T: Clone + Send + Sync + serde::Serialize + serde::de::DeserializeOwned + 'static,
{
    set_context_variable(key, value);
}

fn get_context<T>(key: &str) -> Option<T>
where
    T: Clone + Send + Sync + 'static,
{
    get_context_variable(key)
}

fn update_context<T>(key: &'static str, f: impl FnOnce(T) -> T)
where
    T: Clone + Default + Send + Sync + serde::Serialize + serde::de::DeserializeOwned + 'static,
{
    update_context_variable(key, f);
}

fn snapshot() -> ContextSnapshot {
    capture()
}

fn attach(snap: ContextSnapshot) -> AttachGuard {
    attach_snapshot(snap)
}

fn restore(snap: ContextSnapshot) -> AttachGuard {
    attach_snapshot(snap)
}

fn serialize_context() -> Result<Vec<u8>, ContextError> {
    capture().serialize()
}

fn deserialize_context(bytes: &[u8]) -> Result<AttachGuard, ContextError> {
    ContextSnapshot::deserialize(bytes).map(attach_snapshot)
}

fn snapshot_context<T>(snap: &ContextSnapshot, key: &str) -> Option<T>
where
    T: Clone + Send + Sync + 'static,
{
    snap.values
        .get(key)
        .and_then(|arc| arc.as_any().downcast_ref::<T>().cloned())
}

// ══════════════════════════════════════════════════════════════
//  Registration tests
// ══════════════════════════════════════════════════════════════

#[test]
fn test_register_and_get_default() {
    let key = unique_key("reg_default", "rid");
    register::<RequestId>(key);
    let val: RequestId = get_context::<RequestId>(key).unwrap_or_default();
    assert_eq!(val, RequestId::default());
}

#[test]
fn test_try_register_idempotent() {
    let key = unique_key("reg_idem", "rid");
    try_register::<RequestId>(key).unwrap();
    try_register::<RequestId>(key).unwrap(); // same type = ok
}

#[test]
fn test_try_register_conflict() {
    let key = unique_key("reg_conflict", "val");
    try_register::<RequestId>(key).unwrap();
    let err = try_register::<UserId>(key).unwrap_err();
    assert!(matches!(err, ContextError::AlreadyRegistered(_)));
}

#[test]
fn test_get_unregistered_returns_none() {
    let key = unique_key("unreg_none", "missing");
    assert_eq!(get_context::<RequestId>(key), None);
}

// Registry-validation wrappers like try_get_context were removed in the sync/async split.

// ══════════════════════════════════════════════════════════════
//  Basic get/set tests
// ══════════════════════════════════════════════════════════════

#[test]
fn test_set_and_get() {
    let key = unique_key("set_get", "rid");
    register::<RequestId>(key);
    set_context(key, RequestId("req-42".into()));
    let val: RequestId = get_context::<RequestId>(key).unwrap();
    assert_eq!(val.0, "req-42");
}

// Registry-validation wrappers like try_set_context/try_get_context were removed,
// so the old NotRegistered/TypeMismatch tests no longer apply.

// ══════════════════════════════════════════════════════════════
//  Scope tests
// ══════════════════════════════════════════════════════════════

#[test]
fn test_scope_shadows_and_reverts() {
    let key = unique_key("scope_shadow", "rid");
    register::<RequestId>(key);
    set_context(key, RequestId("parent".into()));

    {
        let _guard = enter_scope();
        set_context(key, RequestId("child".into()));
        assert_eq!(get_context::<RequestId>(key).unwrap().0, "child");
    }
    // Scope reverted
    assert_eq!(get_context::<RequestId>(key).unwrap().0, "parent");
}

#[test]
fn test_nested_scopes() {
    let key = unique_key("nested_scope", "rid");
    register::<RequestId>(key);
    set_context(key, RequestId("root".into()));

    {
        let _g1 = enter_scope();
        set_context(key, RequestId("level1".into()));

        {
            let _g2 = enter_scope();
            set_context(key, RequestId("level2".into()));
            assert_eq!(get_context::<RequestId>(key).unwrap().0, "level2");
        }
        assert_eq!(get_context::<RequestId>(key).unwrap().0, "level1");
    }
    assert_eq!(get_context::<RequestId>(key).unwrap().0, "root");
}

#[test]
fn test_scope_fn() {
    let key = unique_key("scope_fn", "rid");
    register::<RequestId>(key);
    set_context(key, RequestId("before".into()));

    {
        let _scope_guard = enter_scope();
        set_context(key, RequestId("inside".into()));
        assert_eq!(get_context::<RequestId>(key).unwrap().0, "inside");
    }

    assert_eq!(get_context::<RequestId>(key).unwrap().0, "before");
}

#[test]
fn test_scope_inherits_parent() {
    let key = unique_key("scope_inherit", "rid");
    register::<RequestId>(key);
    set_context(key, RequestId("parent_val".into()));

    {
        let _scope_guard = enter_scope();
        // Should see parent value without setting anything
        assert_eq!(get_context::<RequestId>(key).unwrap().0, "parent_val");
    }
}

#[test]
fn test_scope_partial_override() {
    let key_a = unique_key("scope_partial", "a");
    let key_b = unique_key("scope_partial", "b");
    register::<RequestId>(key_a);
    register::<UserId>(key_b);

    set_context(key_a, RequestId("a_parent".into()));
    set_context(key_b, UserId(10));

    {
        let _scope_guard = enter_scope();
        // Override only key_a
        set_context(key_a, RequestId("a_child".into()));
        assert_eq!(get_context::<RequestId>(key_a).unwrap().0, "a_child");
        assert_eq!(get_context::<UserId>(key_b).unwrap().0, 10); // inherited
    }

    assert_eq!(get_context::<RequestId>(key_a).unwrap().0, "a_parent");
    assert_eq!(get_context::<UserId>(key_b).unwrap().0, 10);
}

// ══════════════════════════════════════════════════════════════
//  Snapshot tests
// ══════════════════════════════════════════════════════════════

#[test]
fn test_snapshot_captures_current() {
    let key = unique_key("snap_capture", "rid");
    register::<RequestId>(key);
    set_context(key, RequestId("snapped".into()));

    let snap = snapshot();

    // Modify after snapshot
    set_context(key, RequestId("modified".into()));

    // Attach snapshot in a new scope
    {
        let _guard = attach(snap);
        assert_eq!(get_context::<RequestId>(key).unwrap().0, "snapped");
    }
    // Back to modified
    assert_eq!(get_context::<RequestId>(key).unwrap().0, "modified");
}

#[test]
fn test_snapshot_empty_context() {
    let snap = ContextSnapshot::empty();
    {
        let _guard = attach(snap);
        // No values — should get defaults for registered keys
    }
}

// ══════════════════════════════════════════════════════════════
//  Cross-thread tests
// ══════════════════════════════════════════════════════════════

#[test]
fn test_spawn_with_context() {
    let key = unique_key("thread_spawn", "rid");
    register::<RequestId>(key);
    set_context(key, RequestId("main-thread".into()));

    let snap = snapshot();
    let handle = std::thread::Builder::new()
        .name("test-worker".into())
        .spawn(move || {
            let _guard = restore(snap);
            get_context::<RequestId>(key).unwrap()
        })
        .unwrap();

    let result = handle.join().unwrap();
    assert_eq!(result.0, "main-thread");
}

#[test]
fn test_wrap_with_context_fn_once() {
    let key = unique_key("wrap_once", "rid");
    register::<RequestId>(key);
    set_context(key, RequestId("wrapped".into()));

    let snap = snapshot();
    let wrapped = move || {
        let _guard = restore(snap);
        get_context::<RequestId>(key).unwrap()
    };

    // Change context after wrapping
    set_context(key, RequestId("changed".into()));

    // The wrapped closure should see the snapped value
    let handle = std::thread::spawn(wrapped);
    let result = handle.join().unwrap();
    assert_eq!(result.0, "wrapped");
}

#[test]
fn test_wrap_with_context_fn_multi() {
    let key = unique_key("wrap_multi", "rid");
    register::<RequestId>(key);
    set_context(key, RequestId("multi".into()));

    let snap = snapshot();
    let wrapped = move || {
        let _guard = attach(snap.clone());
        get_context::<RequestId>(key).unwrap()
    };

    // Call multiple times
    let r1 = wrapped();
    let r2 = wrapped();
    assert_eq!(r1.0, "multi");
    assert_eq!(r2.0, "multi");
}

// ══════════════════════════════════════════════════════════════
//  Serialization tests
// ══════════════════════════════════════════════════════════════

#[test]
fn test_serialize_deserialize_roundtrip() {
    let key = unique_key("serde_rt", "rid");
    register::<RequestId>(key);
    set_context(key, RequestId("serialized".into()));

    let bytes = serialize_context().unwrap();

    // Deserialize in a new scope
    {
        let _guard = deserialize_context(&bytes).unwrap();
        assert_eq!(get_context::<RequestId>(key).unwrap().0, "serialized");
    }
}

#[cfg(feature = "base64")]
#[test]
fn test_serialize_deserialize_string_roundtrip() {
    let key = unique_key("serde_str", "rid");
    register::<RequestId>(key);
    set_context(key, RequestId("base64val".into()));

    let encoded = serialize_context()
        .map(|b| base64::engine::general_purpose::STANDARD.encode(&b))
        .map_err(|e| e)
        .unwrap();
    assert!(!encoded.is_empty());

    // Clear and restore
    {
        let _scope_guard = enter_scope();
        set_context(key, RequestId("cleared".into()));
        {
            let bytes = base64::engine::general_purpose::STANDARD
                .decode(&encoded)
                .unwrap();
            let _guard = deserialize_context(&bytes).unwrap();
            assert_eq!(get_context::<RequestId>(key).unwrap().0, "base64val");
        }
    }
}

#[test]
fn test_deserialize_unknown_keys_skipped() {
    let key = unique_key("serde_skip", "rid");
    register::<RequestId>(key);
    set_context(key, RequestId("known".into()));

    // Serialize with the current registration
    let bytes = serialize_context().unwrap();

    // The deserialization should work even if there are extra keys —
    // here we just verify it doesn't fail on the known key.
    {
        let _guard = deserialize_context(&bytes).unwrap();
        assert_eq!(get_context::<RequestId>(key).unwrap().0, "known");
    }
}

#[test]
fn test_serialize_multiple_keys() {
    let key_a = unique_key("serde_multi", "a");
    let key_b = unique_key("serde_multi", "b");
    register::<RequestId>(key_a);
    register::<UserId>(key_b);

    set_context(key_a, RequestId("req-multi".into()));
    set_context(key_b, UserId(42));

    let bytes = serialize_context().unwrap();

    {
        let _scope_guard = enter_scope();
        let _guard = deserialize_context(&bytes).unwrap();
        assert_eq!(get_context::<RequestId>(key_a).unwrap().0, "req-multi");
        assert_eq!(get_context::<UserId>(key_b).unwrap().0, 42);
    }
}

#[test]
fn test_serialize_deserialize_with_isolated_registry() {
    let key_rid = "isolated.serialize.request_id";
    let key_uid = "isolated.serialize.user_id";

    let mut builder = RegistryBuilder::new();
    builder.register::<RequestId>(key_rid);
    builder.register_with::<UserId>(key_uid, |opts| opts.version(2));

    let map = builder.into_map();
    let registry = crate::registry::Registry::new(&map);

    let values: HashMap<&'static str, Arc<dyn ContextValue>> = HashMap::from([
        (
            key_rid,
            Arc::new(RequestId("iso-req".into())) as Arc<dyn ContextValue>,
        ),
        (key_uid, Arc::new(UserId(7)) as Arc<dyn ContextValue>),
    ]);

    let bytes =
        crate::wire::serialize_from(&registry, values, vec!["rpc".into(), "handler".into()])
            .unwrap();

    let snap = crate::wire::deserialize_to_snapshot(&registry, &bytes).unwrap();
    assert_eq!(
        snap.scope_chain(),
        &["rpc".to_string(), "handler".to_string()]
    );
    assert_eq!(
        snapshot_context::<RequestId>(&snap, key_rid),
        Some(RequestId("iso-req".into()))
    );
    assert_eq!(snapshot_context::<UserId>(&snap, key_uid), Some(UserId(7)));
}

#[test]
fn test_capture_with_custom_registry_excludes_local() {
    let key_public = "isolated.capture.public";
    let key_local = "isolated.capture.local";

    let mut builder = RegistryBuilder::new();
    builder.register::<RequestId>(key_public);
    builder.register_with::<UserId>(key_local, |opts| opts.local_only());

    let map = builder.into_map();
    let registry = crate::registry::Registry::new(&map);

    let mut store = ContextStore::new();
    store.set_value(key_public, Arc::new(RequestId("root".into())));
    store.set_value(key_local, Arc::new(UserId(1)));
    store.push_scope(&registry, Some("request".into()));
    store.set_value(key_public, Arc::new(RequestId("child".into())));
    store.set_value(key_local, Arc::new(UserId(2)));

    let snap = crate::capture_with_registry(&store, &registry);

    assert_eq!(snap.scope_chain(), &["request".to_string()]);
    assert_eq!(
        snapshot_context::<RequestId>(&snap, key_public),
        Some(RequestId("child".into()))
    );
    assert_eq!(snapshot_context::<UserId>(&snap, key_local), None);
}

#[test]
fn test_from_snapshot_with_isolated_registry_filters_invalid() {
    let key_valid = "isolated.snapshot.valid";
    let key_local = "isolated.snapshot.local";
    let key_mismatch = "isolated.snapshot.mismatch";
    let key_unknown = "isolated.snapshot.unknown";

    let mut builder = RegistryBuilder::new();
    builder.register::<RequestId>(key_valid);
    builder.register_with::<UserId>(key_local, |opts| opts.local_only());
    builder.register::<UserId>(key_mismatch);

    let map = builder.into_map();
    let registry = crate::registry::Registry::new(&map);

    let values: HashMap<&'static str, Arc<dyn ContextValue>> = HashMap::from([
        (
            key_valid,
            Arc::new(RequestId("keep-me".into())) as Arc<dyn ContextValue>,
        ),
        (key_local, Arc::new(UserId(9)) as Arc<dyn ContextValue>),
        (
            key_mismatch,
            Arc::new(RequestId("wrong-type".into())) as Arc<dyn ContextValue>,
        ),
        (
            key_unknown,
            Arc::new(RequestId("unknown".into())) as Arc<dyn ContextValue>,
        ),
    ]);
    let snap = ContextSnapshot {
        values: Arc::new(values),
        scope_chain: vec!["remote".into()],
    };

    let store = crate::store_from_snapshot_with_registry(snap, &registry);

    assert_eq!(store.scope_chain(), vec!["remote"]);
    assert_eq!(
        store
            .get_value(key_valid)
            .and_then(|arc| arc.as_any().downcast_ref::<RequestId>().cloned()),
        Some(RequestId("keep-me".into()))
    );
    assert!(store.get_value(key_local).is_none());
    assert!(store.get_value(key_mismatch).is_none());
    assert!(store.get_value(key_unknown).is_none());
}

#[test]
fn test_push_scope_caches_with_isolated_registry() {
    let key_cached = "isolated.cache.cached";
    let key_plain = "isolated.cache.plain";

    let mut builder = RegistryBuilder::new();
    builder.register_with::<RequestId>(key_cached, |opts| opts.cached());
    builder.register::<UserId>(key_plain);

    let map = builder.into_map();
    let registry = crate::registry::Registry::new(&map);

    let mut store = ContextStore::new();
    store.set_value(key_cached, Arc::new(RequestId("cached-root".into())));
    store.set_value(key_plain, Arc::new(UserId(42)));

    let depth = store.push_scope(&registry, Some("child".into()));

    assert_eq!(depth, 2);
    assert!(store.current_values.contains_key(key_cached));
    assert!(!store.current_values.contains_key(key_plain));
    assert_eq!(
        store
            .get_value(key_cached)
            .and_then(|arc| arc.as_any().downcast_ref::<RequestId>().cloned()),
        Some(RequestId("cached-root".into()))
    );
    assert_eq!(
        store
            .get_value(key_plain)
            .and_then(|arc| arc.as_any().downcast_ref::<UserId>().cloned()),
        Some(UserId(42))
    );
}

// ══════════════════════════════════════════════════════════════
//  Additional tests (from review feedback S1)
// ══════════════════════════════════════════════════════════════

#[test]
fn test_try_get_registered_but_unset() {
    let key = unique_key("try_get_none", "rid");
    register::<RequestId>(key);
    // Registered but never set — should return Ok(None)
    let result = get_context::<RequestId>(key);
    assert!(result.is_none());
}

// force_thread_local tests removed — sync_ctx always uses thread-local storage

// ══════════════════════════════════════════════════════════════
//  ContextKey<T> tests
// ══════════════════════════════════════════════════════════════

#[cfg(feature = "context-key")]
static TEST_CK_KEY: crate::ContextKey<RequestId> = crate::ContextKey::new("test_ck_rid");

#[cfg(feature = "context-key")]
#[test]
fn test_context_key_register_and_get() {
    register::<RequestId>(TEST_CK_KEY.key());
    TEST_CK_KEY.set(RequestId("ck-val".into()));
    assert_eq!(TEST_CK_KEY.get().unwrap().0, "ck-val");
}

#[cfg(feature = "context-key")]
#[test]
fn test_context_key_try_get_none() {
    let key: crate::ContextKey<UserId> = crate::ContextKey::new(unique_key("ck_none", "uid"));
    register::<UserId>(key.key());
    assert!(key.get().is_none());
}

// ══════════════════════════════════════════════════════════════
//  Macro tests
// ══════════════════════════════════════════════════════════════

#[test]
fn test_register_contexts_macro() {
    // The register_contexts! macro now requires a builder.
    // In tests we use it with a local builder, then merge via free-standing register.
    let key_a = unique_key("macro_reg", "a");
    let key_b = unique_key("macro_reg", "b");
    register::<RequestId>(key_a);
    register::<UserId>(key_b);
    set_context(key_a, RequestId("macro-a".into()));
    set_context(key_b, UserId(77));
    assert_eq!(get_context::<RequestId>(key_a).unwrap().0, "macro-a");
    assert_eq!(get_context::<UserId>(key_b).unwrap().0, 77);
}

// ══════════════════════════════════════════════════════════════
//  Config / size limit tests
// ══════════════════════════════════════════════════════════════

#[test]
fn test_set_max_context_size_enforced() {
    let key = unique_key("size_limit", "rid");
    register::<RequestId>(key);
    set_context(key, RequestId("some-value".into()));

    // Set a very small limit.
    set_max_context_size(5);

    let result = serialize_context();
    assert!(matches!(result, Err(ContextError::ContextTooLarge { .. })));

    // Reset limit.
    set_max_context_size(0);

    // Should succeed now.
    let result = serialize_context();
    assert!(result.is_ok());
}

// ══════════════════════════════════════════════════════════════
//  Version migration tests
// ══════════════════════════════════════════════════════════════

#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)]
struct TraceV1 {
    trace_id: String,
}

#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)]
struct TraceV2 {
    trace_id: String,
    span_id: String,
}

#[test]
fn test_migration_v1_to_v2() {
    let key = unique_key("migrate_v1v2", "trace");

    // Register current version (V2) and add V1 migration.
    register_with::<TraceV2>(key, |o| o.version(2));
    register_migration::<TraceV1, TraceV2>(key, 1, |v1| TraceV2 {
        trace_id: v1.trace_id,
        span_id: "migrated".into(),
    });

    // Serialize V1 bytes manually and run through the migration deserializer.
    let v1_val = TraceV1 {
        trace_id: "tid-old".into(),
    };
    let v1_bytes = bincode::serialize(&v1_val).unwrap();

    let result = crate::registry::with_registration(key, |reg| {
        let deser = reg.deserializers.get(&1).expect("v1 deserializer missing");
        deser(&v1_bytes)
    });

    let boxed = result.unwrap().unwrap();
    let migrated = boxed.as_any().downcast_ref::<TraceV2>().unwrap();
    assert_eq!(migrated.trace_id, "tid-old");
    assert_eq!(migrated.span_id, "migrated");
}

#[test]
fn test_migration_end_to_end() {
    // Full end-to-end: simulate receiving V1 wire bytes when V2 is registered
    // with a V1 migration. Uses a separate thread to get a clean thread-local.
    let key = unique_key("migrate_e2e", "ctx");

    // Register V2 as the current type, with a V1 migration.
    register_with::<TraceV2>(key, |o| o.version(2));
    register_migration::<TraceV1, TraceV2>(key, 1, |v1| TraceV2 {
        trace_id: v1.trace_id,
        span_id: "default-span".into(),
    });

    // Manually craft V1 wire bytes (simulating what a V1 sender would produce).
    let v1_value = TraceV1 {
        trace_id: "from-v1-sender".into(),
    };
    let v1_value_bytes = bincode::serialize(&v1_value).unwrap();
    let wire = make_wire_bytes(key, 1, &v1_value_bytes);

    // Deserialize on a fresh thread (clean thread-local context).
    let handle = std::thread::spawn(move || {
        let _guard = deserialize_context(&wire).unwrap();
        let val: TraceV2 = get_context::<TraceV2>(key).unwrap();
        assert_eq!(val.trace_id, "from-v1-sender");
        assert_eq!(val.span_id, "default-span");
    });
    handle.join().unwrap();
}

#[test]
fn test_migration_unknown_version_errors() {
    let key = unique_key("migrate_unknown", "ctx");
    register_with::<TraceV2>(key, |o| o.version(2));
    // No migration for version 1 registered.

    // Check that version 1 has no deserializer.
    let has_v1 = crate::registry::with_registration(key, |reg| reg.deserializers.contains_key(&1));
    assert_eq!(has_v1, Some(false));
}

#[test]
fn test_migration_current_version_still_works() {
    let key = unique_key("migrate_current", "ctx");
    register_with::<TraceV2>(key, |o| o.version(2));
    register_migration::<TraceV1, TraceV2>(key, 1, |v1| TraceV2 {
        trace_id: v1.trace_id,
        span_id: "migrated".into(),
    });

    // Current version (V2) roundtrip should still work.
    let _guard = enter_scope();
    set_context(
        key,
        TraceV2 {
            trace_id: "current".into(),
            span_id: "current-span".into(),
        },
    );
    let bytes = serialize_context().unwrap();

    {
        let _scope_guard = enter_scope();
        let _guard = deserialize_context(&bytes).unwrap();
        let val: TraceV2 = get_context::<TraceV2>(key).unwrap();
        assert_eq!(val.trace_id, "current");
        assert_eq!(val.span_id, "current-span");
    }
}

#[test]
fn test_migration_rejects_current_version() {
    let key = unique_key("migrate_reject", "ctx");
    register_with::<TraceV2>(key, |o| o.version(2));

    // Attempting to register a migration for the CURRENT version should fail.
    let result = try_register_migration::<TraceV1, TraceV2>(key, 2, |v1| TraceV2 {
        trace_id: v1.trace_id,
        span_id: "should-fail".into(),
    });
    assert!(result.is_err());
    let err = result.unwrap_err();
    assert!(matches!(err, ContextError::DeserializationFailed(_)));
}

// ══════════════════════════════════════════════════════════════
//  Custom codec tests
// ══════════════════════════════════════════════════════════════

#[test]
fn test_register_with_json_codec() {
    let key = unique_key("codec_json", "rid");

    register_with::<RequestId>(key, |o| {
        o.codec(
            |val| serde_json::to_vec(val).map_err(|e| e.to_string()),
            |bytes| serde_json::from_slice(bytes).map_err(|e| e.to_string()),
        )
    });

    let _guard = enter_scope();
    set_context(key, RequestId("json-encoded".into()));

    // Roundtrip through serialization — uses JSON codec, not bincode.
    let bytes = serialize_context().unwrap();
    {
        let _scope_guard = enter_scope();
        let _guard = deserialize_context(&bytes).unwrap();
        let val: RequestId = get_context::<RequestId>(key).unwrap();
        assert_eq!(val.0, "json-encoded");
    }
}

#[test]
fn test_json_codec_wire_bytes_are_json() {
    let key = unique_key("codec_json_verify", "rid");

    register_with::<RequestId>(key, |o| {
        o.codec(
            |val| serde_json::to_vec(val).map_err(|e| e.to_string()),
            |bytes| serde_json::from_slice(bytes).map_err(|e| e.to_string()),
        )
    });

    let _guard = enter_scope();
    set_context(key, RequestId("verify-json".into()));

    let wire_bytes = serialize_context().unwrap();

    // The inner value bytes should be valid JSON, not bincode.
    // Deserialize on a fresh thread to confirm.
    let handle = std::thread::spawn(move || {
        register_with::<RequestId>(key, |o| {
            o.codec(
                |val| serde_json::to_vec(val).map_err(|e| e.to_string()),
                |bytes| serde_json::from_slice(bytes).map_err(|e| e.to_string()),
            )
        });
        let _guard = deserialize_context(&wire_bytes).unwrap();
        let val: RequestId = get_context::<RequestId>(key).unwrap();
        assert_eq!(val.0, "verify-json");
    });
    handle.join().unwrap();
}

#[test]
fn test_default_codec_still_works() {
    // Ensure normal registration (bincode) is unaffected by codec feature.
    let key = unique_key("codec_default", "rid");
    register::<RequestId>(key);

    let _guard = enter_scope();
    set_context(key, RequestId("bincode-default".into()));

    let bytes = serialize_context().unwrap();
    {
        let _scope_guard = enter_scope();
        let _guard = deserialize_context(&bytes).unwrap();
        let val: RequestId = get_context::<RequestId>(key).unwrap();
        assert_eq!(val.0, "bincode-default");
    }
}

#[test]
fn test_local_only_rejects_codec() {
    let key = unique_key("local_codec", "rid");
    let result = try_register_with::<RequestId>(key, |o| {
        o.local_only().codec(
            |val| serde_json::to_vec(val).map_err(|e| e.to_string()),
            |bytes| serde_json::from_slice(bytes).map_err(|e| e.to_string()),
        )
    });
    assert!(result.is_err());
    assert!(matches!(
        result.unwrap_err(),
        ContextError::SerializationFailed(_)
    ));
}

#[test]
fn test_local_only_rejects_version() {
    let key = unique_key("local_version", "rid");
    let result = try_register_with::<RequestId>(key, |o| o.local_only().version(2));
    assert!(result.is_err());
    assert!(matches!(
        result.unwrap_err(),
        ContextError::SerializationFailed(_)
    ));
}

#[test]
fn test_local_only_builder_excludes_from_serialization() {
    let key = unique_key("local_builder_ser", "rid");
    register_with::<RequestId>(key, |o| o.local_only());

    let _scope = enter_scope();
    set_context(key, RequestId("should-not-serialize".into()));

    // Serialize — the local_only value must be excluded from wire bytes.
    let bytes = serialize_context().unwrap();

    // Deserialize on a fresh thread so the original scope's value isn't visible.
    std::thread::spawn(move || {
        let _guard = deserialize_context(&bytes).unwrap();
        let val = get_context::<RequestId>(key);
        assert!(
            val.is_none(),
            "local_only value registered via builder should not survive serialization"
        );
    })
    .join()
    .unwrap();
}

// ══════════════════════════════════════════════════════════════
//  Async tests (tokio)
// ══════════════════════════════════════════════════════════════

mod async_tests {
    use super::*;

    #[tokio::test]
    async fn test_with_context_basic() {
        let key = unique_key("async_basic", "rid");
        register::<RequestId>(key);

        let snap = {
            set_context(key, RequestId("async-val".into()));
            snapshot()
        };

        let result = with_snapshot(snap, async { get_context::<RequestId>(key).unwrap() }).await;

        assert_eq!(result.0, "async-val");
    }

    #[tokio::test]
    async fn test_scope_async() {
        let key = unique_key("scope_async", "rid");
        register::<RequestId>(key);

        let snap = {
            set_context(key, RequestId("before-async".into()));
            snapshot()
        };

        with_snapshot(snap, async {
            assert_eq!(get_context::<RequestId>(key).unwrap().0, "before-async");

            async_scope("", async {
                set_context(key, RequestId("inside-async".into()));
                assert_eq!(get_context::<RequestId>(key).unwrap().0, "inside-async");
            })
            .await;

            assert_eq!(get_context::<RequestId>(key).unwrap().0, "before-async");
        })
        .await;
    }

    #[tokio::test]
    async fn test_spawn_with_context_async() {
        let key = unique_key("async_spawn", "rid");
        register::<RequestId>(key);

        let snap = {
            set_context(key, RequestId("spawned-async".into()));
            snapshot()
        };

        let handle = with_snapshot(snap, async {
            let child_snap = snapshot();
            tokio::spawn(with_snapshot(child_snap, async {
                get_context::<RequestId>(key).unwrap()
            }))
        })
        .await;

        let result = handle.await.unwrap();
        assert_eq!(result.0, "spawned-async");
    }

    #[tokio::test]
    async fn test_async_scope_isolation() {
        let key = unique_key("async_scope_iso", "rid");
        register::<RequestId>(key);

        let snap = {
            set_context(key, RequestId("outer".into()));
            snapshot()
        };

        with_snapshot(snap, async {
            assert_eq!(get_context::<RequestId>(key).unwrap().0, "outer");

            async_scope("", async {
                set_context(key, RequestId("inner".into()));
                assert_eq!(get_context::<RequestId>(key).unwrap().0, "inner");
            })
            .await;

            assert_eq!(get_context::<RequestId>(key).unwrap().0, "outer");
        })
        .await;
    }

    #[tokio::test]
    async fn test_async_serialize_roundtrip() {
        let key = unique_key("async_serde", "rid");
        register::<RequestId>(key);

        let snap = {
            set_context(key, RequestId("async-serde".into()));
            snapshot()
        };

        with_snapshot(snap, async {
            let bytes = serialize_context().unwrap();
            set_context(key, RequestId("cleared".into()));
            let _guard = deserialize_context(&bytes).unwrap();
            assert_eq!(get_context::<RequestId>(key).unwrap().0, "async-serde");
        })
        .await;
    }
}

// ══════════════════════════════════════════════════════════════
//  Scope chain tests
// ══════════════════════════════════════════════════════════════

#[test]
fn test_scope_chain_empty_by_default() {
    let chain = scope_chain();
    assert!(chain.is_empty(), "default scope chain should be empty");
}

#[test]
fn test_scope_chain_named_scope() {
    let _g = enter_named_scope("outer");
    assert_eq!(scope_chain(), vec!["outer"]);
    {
        let _g2 = enter_named_scope("inner");
        assert_eq!(scope_chain(), vec!["outer", "inner"]);
    }
    assert_eq!(scope_chain(), vec!["outer"]);
}

#[test]
fn test_scope_chain_unnamed_invisible() {
    let _g1 = enter_named_scope("named");
    let _g2 = enter_scope();
    let _g3 = enter_named_scope("also-named");
    assert_eq!(scope_chain(), vec!["named", "also-named"]);
}

#[test]
fn test_scope_chain_snapshot_preserves_chain() {
    let _g = enter_named_scope("request-handler");
    let snap = snapshot();
    assert_eq!(snap.scope_chain, vec!["request-handler"]);

    // Restore in a new scope — the chain becomes remote_chain
    {
        let _scope_guard = enter_scope();
        let _guard = attach(snap.clone());
        assert_eq!(scope_chain(), vec!["request-handler"]);

        // Push local named scopes
        let _g2 = enter_named_scope("sub-handler");
        assert_eq!(scope_chain(), vec!["request-handler", "sub-handler"]);
    }
}

#[test]
fn test_scope_chain_serialize_roundtrip() {
    let key = unique_key("sc_serde", "rid");
    register::<RequestId>(key);

    let _g1 = enter_named_scope("app");
    let _g2 = enter_named_scope("service");
    set_context(key, RequestId("req-1".into()));

    let bytes = serialize_context().unwrap();

    // Deserialize in a clean scope
    {
        let _scope_guard = enter_scope();
        let _guard = deserialize_context(&bytes).unwrap();
        // Values restored
        assert_eq!(get_context::<RequestId>(key).unwrap().0, "req-1");
        // Scope chain restored as remote prefix
        assert_eq!(scope_chain(), vec!["app", "service"]);

        // Push more local scopes
        let _g3 = enter_named_scope("handler");
        assert_eq!(scope_chain(), vec!["app", "service", "handler"]);
    }
}

#[test]
fn test_scope_chain_wire_v1_compat() {
    let key = unique_key("sc_v1", "rid");
    register::<RequestId>(key);

    // Create v1 wire bytes (no scope chain)
    let value_bytes = bincode::serialize(&RequestId("v1-value".into())).unwrap();
    let v1_bytes = make_wire_bytes_v(1, key, 1, &value_bytes);

    {
        let _scope_guard = enter_scope();
        let _guard = deserialize_context(&v1_bytes).unwrap();
        assert_eq!(get_context::<RequestId>(key).unwrap().0, "v1-value");
        // No scope chain from v1
        assert!(scope_chain().is_empty());
    }
}

#[test]
fn test_scope_chain_remote_chain_lifo_restore() {
    // Simulate nested deserialization (e.g., nested remote calls)
    let key = unique_key("sc_lifo", "rid");
    register::<RequestId>(key);

    let _g = enter_named_scope("local-root");

    // First "remote" call
    let _g1 = enter_named_scope("sender-scope");
    set_context(key, RequestId("first".into()));
    let bytes1 = serialize_context().unwrap();

    {
        let _scope_guard = enter_scope();
        let _guard1 = deserialize_context(&bytes1).unwrap();
        // Chain shows the sender's full chain
        assert_eq!(scope_chain(), vec!["local-root", "sender-scope"]);

        // Second nested "remote" call
        let _g2 = enter_named_scope("nested-scope");
        let bytes2 = serialize_context().unwrap();

        {
            let _scope_guard = enter_scope();
            let _guard2 = deserialize_context(&bytes2).unwrap();
            assert_eq!(
                scope_chain(),
                vec!["local-root", "sender-scope", "nested-scope"]
            );
        }

        // After inner scope ends, original chain is restored
        assert_eq!(
            scope_chain(),
            vec!["local-root", "sender-scope", "nested-scope"]
        );
    }
}

mod async_scope_chain_tests {
    use super::*;

    #[tokio::test]
    async fn test_scope_chain_with_context() {
        let _g = enter_named_scope("pre-send");
        let snap = snapshot();

        with_snapshot(snap, async {
            assert_eq!(scope_chain(), vec!["pre-send"]);

            async_scope("handler", async {
                assert_eq!(scope_chain(), vec!["pre-send", "handler"]);
            })
            .await;
        })
        .await;
    }

    #[tokio::test]
    async fn test_named_scope_async_basic() {
        let snap = {
            let _g = enter_named_scope("root");
            snapshot()
        };

        with_snapshot(snap, async {
            async_scope("level-1", async {
                assert_eq!(scope_chain(), vec!["root", "level-1"]);

                async_scope("level-2", async {
                    assert_eq!(scope_chain(), vec!["root", "level-1", "level-2"]);
                })
                .await;
            })
            .await;
        })
        .await;
    }
}

// ══════════════════════════════════════════════════════════════
//  Re-entrancy and contention-free safety tests
// ══════════════════════════════════════════════════════════════
//
// These tests verify that the Cell<Option<ContextStore>> design handles
// re-entrant access gracefully: no panics, no corrupted state.

/// A value whose Drop impl reads from context.
#[derive(Clone, Default, Debug, Serialize, Deserialize)]
struct ReentrantDropVal(String);

impl Drop for ReentrantDropVal {
    fn drop(&mut self) {
        // Try to read context during drop. Should not panic.
        // Probe during Drop without panicking if the key is missing.
        // (this Drop may fire after tests clean up).
        let _ = get_context::<RequestId>("__reentrant_drop_probe__");
    }
}

#[test]
fn test_reentrant_read_during_scope_enter() {
    // Reading context during scope enter should not panic.
    let key = unique_key("reentrant_enter", "rid");
    register::<RequestId>(key);

    set_context(key, RequestId("parent-val".into()));

    // Enter a scope — internally takes the store, modifies it, puts it back.
    // If anything tries to read during the take window, it should gracefully
    // return defaults (not panic).
    let _g = enter_scope();

    // Value should still be accessible from parent scope.
    let val: RequestId = get_context::<RequestId>(key).unwrap();
    assert_eq!(val.0, "parent-val");
}

#[test]
fn test_reentrant_read_during_scope_leave() {
    // Dropping a ScopeGuard triggers leave_scope. Reading context during
    // the leave should not panic.
    let key = unique_key("reentrant_leave", "rid");
    register::<RequestId>(key);

    set_context(key, RequestId("base".into()));

    {
        let _g = enter_scope();
        set_context(key, RequestId("child".into()));
        assert_eq!(get_context::<RequestId>(key).unwrap().0, "child");
    }
    // _g dropped — scope popped. Old child value (Arc) dropped OUTSIDE Cell window.

    let val: RequestId = get_context::<RequestId>(key).unwrap();
    assert_eq!(val.0, "base");
}

#[test]
fn test_reentrant_read_during_set_context() {
    // set_context takes the store briefly. A concurrent read (simulated
    // sequentially since we're single-threaded) should be safe.
    let key_a = unique_key("reentrant_set", "a");
    let key_b = unique_key("reentrant_set", "b");
    register::<RequestId>(key_a);
    register::<RequestId>(key_b);

    set_context(key_a, RequestId("aaa".into()));
    set_context(key_b, RequestId("bbb".into()));

    // After set, both reads succeed.
    assert_eq!(get_context::<RequestId>(key_a).unwrap().0, "aaa");
    assert_eq!(get_context::<RequestId>(key_b).unwrap().0, "bbb");
}

#[test]
fn test_reentrant_drop_on_value_overwrite() {
    // When a value is overwritten, the old Arc is dropped outside the Cell
    // window. If the old value's Drop reads context, it should not panic.
    let key = unique_key("reentrant_drop_overwrite", "val");
    register::<ReentrantDropVal>(key);

    set_context(key, ReentrantDropVal("first".into()));
    // This overwrites "first" — the old Arc is dropped after Cell::set().
    // ReentrantDropVal::drop tries to read context → should not panic.
    set_context(key, ReentrantDropVal("second".into()));

    let val: ReentrantDropVal = get_context::<ReentrantDropVal>(key).unwrap();
    assert_eq!(val.0, "second");
}

#[test]
fn test_reentrant_drop_on_scope_leave() {
    // When a scope is popped, the old current_values HashMap is dropped
    // outside the Cell window. Values' Drop impls should not panic.
    let key = unique_key("reentrant_drop_leave", "val");
    register::<ReentrantDropVal>(key);

    set_context(key, ReentrantDropVal("root".into()));

    {
        let _g = enter_scope();
        set_context(key, ReentrantDropVal("child-scope".into()));
    }
    // _g dropped → child scope's ReentrantDropVal dropped.
    // Its Drop reads context → should not panic.

    let val: ReentrantDropVal = get_context::<ReentrantDropVal>(key).unwrap();
    assert_eq!(val.0, "root");
}

#[test]
fn test_scope_push_pop_integrity_across_many_levels() {
    // Rapidly push/pop many scopes to stress the Cell take/set pattern.
    let key = unique_key("stress_scope", "rid");
    register::<RequestId>(key);

    set_context(key, RequestId("root".into()));

    let depth = 50;
    let mut guards: Vec<ScopeGuard> = Vec::new();

    for i in 0..depth {
        guards.push(enter_named_scope(format!("scope-{}", i)));
        set_context(key, RequestId(format!("val-{}", i)));
    }

    // Innermost scope value.
    assert_eq!(
        get_context::<RequestId>(key).unwrap().0,
        format!("val-{}", depth - 1)
    );

    // Pop all scopes in reverse.
    for i in (0..depth).rev() {
        guards.pop();
        if i > 0 {
            assert_eq!(
                get_context::<RequestId>(key).unwrap().0,
                format!("val-{}", i - 1)
            );
        }
    }

    // Back to root.
    assert_eq!(get_context::<RequestId>(key).unwrap().0, "root");
}

#[test]
fn test_scope_chain_integrity_after_many_push_pops() {
    // Verify scope_chain is correct after many push/pop cycles.
    let key = unique_key("chain_stress", "rid");
    register::<RequestId>(key);

    for round in 0..10 {
        let name = format!("round-{}", round);
        let _g = enter_named_scope(&name);
        let chain = scope_chain();
        assert!(chain.last().map(|s| s.as_str()) == Some(name.as_str()));
    }
    // All guards dropped, chain should be empty.
    assert!(scope_chain().is_empty());
}

#[test]
fn test_update_context_basic() {
    let key = unique_key("update_ctx", "counter");

    #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)]
    struct Counter(u64);

    register::<Counter>(key);

    set_context(key, Counter(10));

    // Update: increment the counter.
    update_context::<Counter>(key, |c| Counter(c.0 + 5));

    let val = get_context::<Counter>(key).unwrap();
    assert_eq!(val.0, 15);
}

#[test]
fn test_update_context_default_when_unset() {
    let key = unique_key("update_default", "counter");

    #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)]
    struct Counter(u64);

    register::<Counter>(key);

    // No prior set — should start from default (0).
    update_context::<Counter>(key, |c| Counter(c.0 + 1));

    let val = get_context::<Counter>(key).unwrap();
    assert_eq!(val.0, 1);
}

#[test]
fn test_update_context_callback_can_read_other_keys() {
    // The callback in update_context runs with the store available,
    // so reading other keys should work.
    let key_a = unique_key("update_read_other", "a");
    let key_b = unique_key("update_read_other", "b");
    register::<RequestId>(key_a);
    register::<RequestId>(key_b);

    set_context(key_a, RequestId("aaa".into()));
    set_context(key_b, RequestId("bbb".into()));

    // Update key_a, reading key_b inside the callback.
    update_context::<RequestId>(key_a, |_old| {
        let b = get_context::<RequestId>(key_b).unwrap();
        RequestId(format!("merged-{}", b.0))
    });

    assert_eq!(get_context::<RequestId>(key_a).unwrap().0, "merged-bbb");
    // key_b unchanged.
    assert_eq!(get_context::<RequestId>(key_b).unwrap().0, "bbb");
}

#[test]
fn test_update_context_in_scope_reverts() {
    let key = unique_key("update_scope_revert", "val");

    #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)]
    struct Val(String);

    register::<Val>(key);

    set_context(key, Val("root".into()));

    {
        let _g = enter_scope();
        update_context::<Val>(key, |_| Val("updated-in-child".into()));
        assert_eq!(get_context::<Val>(key).unwrap().0, "updated-in-child");
    }

    // Reverted after scope exit.
    assert_eq!(get_context::<Val>(key).unwrap().0, "root");
}

#[test]
fn test_get_context_option_some_and_none() {
    let key_set = unique_key("get_opt", "set");
    let key_unset = unique_key("get_opt", "unset");
    register::<RequestId>(key_set);
    register::<RequestId>(key_unset);

    set_context(key_set, RequestId("hello".into()));

    assert_eq!(
        get_context::<RequestId>(key_set),
        Some(RequestId("hello".into()))
    );
    assert_eq!(get_context::<RequestId>(key_unset), None);
}

#[test]
fn test_snapshot_uses_arc_sharing() {
    // After the Arc migration, snapshot values share memory with the store.
    // This test verifies snapshot + attach works correctly.
    let key = unique_key("snap_arc", "rid");
    register::<RequestId>(key);

    set_context(key, RequestId("original".into()));
    let snap = snapshot();

    // Modify after snapshot.
    set_context(key, RequestId("modified".into()));

    // Attach restores snapshot values.
    {
        let _g = attach(snap);
        assert_eq!(get_context::<RequestId>(key).unwrap().0, "original");
    }

    // After attach scope ends, current value is back.
    assert_eq!(get_context::<RequestId>(key).unwrap().0, "modified");
}

#[test]
fn test_concurrent_scope_and_read_no_panic() {
    // Simulate the pattern that caused BorrowError in v0.3.x:
    // A tracing callback fires during a write, triggering a re-entrant read.
    // With Cell<Option<ContextStore>>, this returns defaults instead of panicking.
    let key = unique_key("concurrent_rw", "rid");
    register::<RequestId>(key);

    set_context(key, RequestId("base".into()));

    // Rapidly alternate set + get (simulating interleaved callbacks).
    for i in 0..100 {
        set_context(key, RequestId(format!("iter-{}", i)));
        let val: RequestId = get_context::<RequestId>(key).unwrap();
        assert_eq!(val.0, format!("iter-{}", i));
    }
}

#[test]
fn test_cached_key_o1_read_in_nested_scopes() {
    // Cached keys should always be in current_values after scope entry.
    let key = unique_key("cached_read", "rid");
    register_with::<RequestId>(key, |opts| opts.cached());

    set_context(key, RequestId("root-val".into()));

    let _g1 = enter_scope();
    // Cached key should be readable without walking parents.
    assert_eq!(get_context::<RequestId>(key).unwrap().0, "root-val");

    let _g2 = enter_scope();
    assert_eq!(get_context::<RequestId>(key).unwrap().0, "root-val");

    // Override in inner scope.
    set_context(key, RequestId("inner-val".into()));
    assert_eq!(get_context::<RequestId>(key).unwrap().0, "inner-val");

    drop(_g2);
    // After inner scope exit, cached value from g1's scope is restored.
    assert_eq!(get_context::<RequestId>(key).unwrap().0, "root-val");

    drop(_g1);
    assert_eq!(get_context::<RequestId>(key).unwrap().0, "root-val");
}

#[test]
fn test_non_cached_key_walks_parents() {
    // Non-cached keys (default) should find values in parent scopes.
    let key = unique_key("non_cached", "rid");
    register::<RequestId>(key);

    set_context(key, RequestId("root-val".into()));

    let _g1 = enter_scope();
    // Not set in child scope — walks to root.
    assert_eq!(get_context::<RequestId>(key).unwrap().0, "root-val");

    // Override in child.
    set_context(key, RequestId("child-val".into()));
    assert_eq!(get_context::<RequestId>(key).unwrap().0, "child-val");

    let _g2 = enter_scope();
    // Grandchild walks to child.
    assert_eq!(get_context::<RequestId>(key).unwrap().0, "child-val");

    drop(_g2);
    assert_eq!(get_context::<RequestId>(key).unwrap().0, "child-val");

    drop(_g1);
    assert_eq!(get_context::<RequestId>(key).unwrap().0, "root-val");
}

#[tokio::test]
async fn test_async_reentrant_safety() {
    // Verify that scope_async and named_scope_async don't panic
    // under re-entrant-like patterns.
    let key = unique_key("async_reentrant", "rid");
    register::<RequestId>(key);

    let snap = {
        set_context(key, RequestId("base".into()));
        snapshot()
    };

    with_snapshot(snap, async {
        assert_eq!(get_context::<RequestId>(key).unwrap().0, "base");

        async_scope("", async {
            set_context(key, RequestId("in-scope-async".into()));
            assert_eq!(get_context::<RequestId>(key).unwrap().0, "in-scope-async");

            async_scope("inner", async {
                assert_eq!(get_context::<RequestId>(key).unwrap().0, "in-scope-async");
                set_context(key, RequestId("deep".into()));
                assert_eq!(get_context::<RequestId>(key).unwrap().0, "deep");
            })
            .await;

            assert_eq!(get_context::<RequestId>(key).unwrap().0, "in-scope-async");
        })
        .await;

        assert_eq!(get_context::<RequestId>(key).unwrap().0, "base");
    })
    .await;
}

// ══════════════════════════════════════════════════════════════
//  Fork tests
// ══════════════════════════════════════════════════════════════

#[tokio::test]
async fn test_fork_reads_parent_values() {
    let key = unique_key("fork_read", "rid");
    register::<RequestId>(key);

    let snap = {
        let _scope = enter_scope();
        set_context(key, RequestId("parent-val".into()));
        snapshot()
    };

    let result = with_snapshot(snap, async { get_context::<RequestId>(key).unwrap() }).await;

    assert_eq!(result.0, "parent-val");
}

#[tokio::test]
async fn test_fork_writes_are_isolated() {
    let key = unique_key("fork_isolate", "rid");
    register::<RequestId>(key);

    let snap = {
        let _scope = enter_scope();
        set_context(key, RequestId("parent".into()));
        snapshot()
    };

    with_snapshot(snap, async {
        set_context(key, RequestId("child-override".into()));
        let val = get_context::<RequestId>(key).unwrap();
        assert_eq!(val.0, "child-override");
    })
    .await;

    let parent_val = get_context::<RequestId>(key).unwrap_or_default();
    assert_eq!(parent_val, RequestId::default());
}

#[tokio::test]
async fn test_fork_is_cheap_clone() {
    let key = unique_key("fork_clone", "rid");
    register::<RequestId>(key);

    let snap = {
        let _scope = enter_scope();
        set_context(key, RequestId("shared".into()));
        snapshot()
    };

    let snap2 = snap.clone();

    let r1 = with_snapshot(snap, async { get_context::<RequestId>(key).unwrap() }).await;
    let r2 = with_snapshot(snap2, async { get_context::<RequestId>(key).unwrap() }).await;

    assert_eq!(r1.0, "shared");
    assert_eq!(r2.0, "shared");
}

#[tokio::test]
async fn test_fork_child_scopes_work() {
    let key = unique_key("fork_scope", "rid");
    register::<RequestId>(key);

    let snap = {
        let _scope = enter_scope();
        set_context(key, RequestId("base".into()));
        snapshot()
    };

    with_snapshot(snap, async {
        assert_eq!(get_context::<RequestId>(key).unwrap().0, "base");

        async_scope("", async {
            set_context(key, RequestId("inner".into()));
            assert_eq!(get_context::<RequestId>(key).unwrap().0, "inner");
        })
        .await;

        assert_eq!(get_context::<RequestId>(key).unwrap().0, "base");
    })
    .await;
}

#[tokio::test]
async fn test_spawn_with_fork_async() {
    let key = unique_key("fork_spawn", "rid");
    register::<RequestId>(key);

    let snap = {
        let _scope = enter_scope();
        set_context(key, RequestId("for-spawn".into()));
        snapshot()
    };

    let join = tokio::spawn(with_snapshot(snap, async {
        get_context::<RequestId>(key).unwrap()
    }));

    let result = join.await.unwrap();
    assert_eq!(result.0, "for-spawn");
}

#[tokio::test]
async fn test_fork_empty_context() {
    let snap = ContextSnapshot::empty();

    with_snapshot(snap, async {
        // No values set — empty context should be attachable.
    })
    .await;
}

#[tokio::test]
async fn test_fork_scope_chain_preserved() {
    let key = unique_key("fork_chain", "rid");
    register::<RequestId>(key);

    let snap = {
        let _scope = enter_named_scope("parent-scope");
        set_context(key, RequestId("chained".into()));
        snapshot()
    };

    with_snapshot(snap, async {
        let chain = scope_chain();
        assert!(
            chain.contains(&"parent-scope".to_string()),
            "snapshot should preserve parent scope chain: {:?}",
            chain
        );
    })
    .await;
}

// ══════════════════════════════════════════════════════════════
//  merge_with tests
// ══════════════════════════════════════════════════════════════

#[test]
fn test_merge_with_adds_values() {
    let key = unique_key("merge_add", "rid");
    register::<RequestId>(key);

    // Create a store with a value
    let snap = {
        let _scope = enter_scope();
        set_context(key, RequestId("merged-val".into()));
        snapshot()
    };
    let source: crate::store::ContextStore = snap.into();

    // Clear context and merge
    clear();
    crate::merge_with(source);

    assert_eq!(get_context::<RequestId>(key).unwrap().0, "merged-val");
}

#[test]
fn test_merge_with_overwrites_existing() {
    let key = unique_key("merge_overwrite", "rid");
    register::<RequestId>(key);

    set_context(key, RequestId("original".into()));

    let snap = {
        let _scope = enter_scope();
        set_context(key, RequestId("new-val".into()));
        snapshot()
    };
    let source: crate::store::ContextStore = snap.into();

    crate::merge_with(source);

    assert_eq!(get_context::<RequestId>(key).unwrap().0, "new-val");
}

// ══════════════════════════════════════════════════════════════
//  capture() local-only exclusion tests
// ══════════════════════════════════════════════════════════════

#[test]
fn test_capture_excludes_local_only() {
    let key_remote = unique_key("cap_local", "remote");
    let key_local = unique_key("cap_local", "local");
    register::<RequestId>(key_remote);
    register_with::<RequestId>(key_local, |o| o.local_only());

    set_context(key_remote, RequestId("remote-val".into()));
    set_context(key_local, RequestId("local-val".into()));

    let snap = capture();
    // Remote key should be in snapshot
    assert!(snap.values.contains_key(key_remote));
    // Local-only key should NOT be in snapshot
    assert!(!snap.values.contains_key(key_local));
}

#[test]
fn test_fork_preserves_local_only() {
    let key_local = unique_key("fork_local", "local");
    register_with::<RequestId>(key_local, |o| o.local_only());

    set_context(key_local, RequestId("local-val".into()));

    // Fork should preserve all values including local-only
    let forked = crate::fork();
    let _g = crate::attach_store(forked);
    assert_eq!(get_context::<RequestId>(key_local).unwrap().0, "local-val");
}

// ══════════════════════════════════════════════════════════════
//  From<ContextSnapshot> registry validation tests
// ══════════════════════════════════════════════════════════════

#[test]
fn test_snapshot_to_store_filters_unknown_keys() {
    let key = unique_key("snap_filter", "known");
    register::<RequestId>(key);

    // Manually construct a snapshot with an unknown key
    let mut values = std::collections::HashMap::new();
    values.insert(
        key,
        std::sync::Arc::new(RequestId("known-val".into()))
            as std::sync::Arc<dyn crate::value::ContextValue>,
    );
    values.insert(
        "totally_unknown_key_xyz",
        std::sync::Arc::new(RequestId("ghost".into()))
            as std::sync::Arc<dyn crate::value::ContextValue>,
    );

    let snap = ContextSnapshot {
        values: std::sync::Arc::new(values),
        scope_chain: vec![],
    };

    let store: crate::store::ContextStore = snap.into();
    let all = store.collect_values();

    // Known key should be present
    assert!(all.contains_key(key));
    // Unknown key should be filtered out
    assert!(!all.contains_key("totally_unknown_key_xyz"));
}

#[test]
fn test_snapshot_to_store_filters_local_keys() {
    let key_local = unique_key("snap_local_filter", "local");
    register_with::<RequestId>(key_local, |o| o.local_only());

    // Even if a snapshot somehow has a local key, converting to store filters it
    let mut values = std::collections::HashMap::new();
    values.insert(
        key_local,
        std::sync::Arc::new(RequestId("local-ghost".into()))
            as std::sync::Arc<dyn crate::value::ContextValue>,
    );

    let snap = ContextSnapshot {
        values: std::sync::Arc::new(values),
        scope_chain: vec![],
    };

    let store: crate::store::ContextStore = snap.into();
    let all = store.collect_values();

    assert!(!all.contains_key(key_local));
}

// ══════════════════════════════════════════════════════════════
//  ContextFutureExt trait method tests
// ══════════════════════════════════════════════════════════════

#[tokio::test]
async fn test_future_ext_attach() {
    let key = unique_key("fut_attach", "rid");
    register::<RequestId>(key);

    let snap = {
        let _scope = enter_scope();
        set_context(key, RequestId("attached".into()));
        snapshot()
    };

    let result = async { get_context::<RequestId>(key).unwrap() }
        .attach(snap)
        .await;

    assert_eq!(result.0, "attached");
}

#[tokio::test]
async fn test_future_ext_fork() {
    let key = unique_key("fut_fork", "rid");
    register::<RequestId>(key);

    // Set up context with a value
    let snap = {
        let _scope = enter_scope();
        set_context(key, RequestId("parent-val".into()));
        snapshot()
    };

    with_snapshot(snap, async {
        // Fork inherits parent values
        let result = async {
            let val = get_context::<RequestId>(key).unwrap();
            // Write in fork is isolated
            set_context(key, RequestId("forked".into()));
            val
        }
        .fork()
        .await;

        assert_eq!(result.0, "parent-val");
        // Parent value unchanged
        assert_eq!(get_context::<RequestId>(key).unwrap().0, "parent-val");
    })
    .await;
}

#[tokio::test]
async fn test_future_ext_scope() {
    let key = unique_key("fut_scope", "rid");
    register::<RequestId>(key);

    let snap = {
        let _scope = enter_scope();
        set_context(key, RequestId("base".into()));
        snapshot()
    };

    with_snapshot(snap, async {
        let chain = async {
            set_context(key, RequestId("scoped".into()));
            scope_chain()
        }
        .scope("my-scope")
        .await;

        assert!(chain.contains(&"my-scope".to_string()));
        // Parent value not affected by scoped write
        assert_eq!(get_context::<RequestId>(key).unwrap().0, "base");
    })
    .await;
}

#[tokio::test]
async fn test_future_ext_capture() {
    let key = unique_key("fut_capture", "rid");
    register::<RequestId>(key);

    let snap = {
        let _scope = enter_scope();
        set_context(key, RequestId("original".into()));
        snapshot()
    };

    with_snapshot(snap, async {
        let result = async { get_context::<RequestId>(key).unwrap() }
            .capture()
            .await;

        assert_eq!(result.0, "original");
    })
    .await;
}

// ══════════════════════════════════════════════════════════════
//  update_context_variable tests
// ══════════════════════════════════════════════════════════════

#[test]
fn test_update_context_variable_modifies_value() {
    let key = unique_key("update_mod", "uid");
    register::<UserId>(key);

    set_context(key, UserId(10));
    update_context(key, |v: UserId| UserId(v.0 + 5));

    assert_eq!(get_context::<UserId>(key).unwrap().0, 15);
}

#[test]
fn test_update_context_variable_uses_default_when_missing() {
    let key = unique_key("update_default", "uid");
    register::<UserId>(key);

    // No value set — update should use Default (0)
    update_context(key, |v: UserId| UserId(v.0 + 42));

    assert_eq!(get_context::<UserId>(key).unwrap().0, 42);
}

// ══════════════════════════════════════════════════════════════
//  clear() tests
// ══════════════════════════════════════════════════════════════

#[test]
fn test_clear_removes_all_values() {
    let key = unique_key("clear_all", "rid");
    register::<RequestId>(key);

    set_context(key, RequestId("before-clear".into()));
    assert!(get_context::<RequestId>(key).is_some());

    clear();

    assert_eq!(get_context::<RequestId>(key), None);
}

#[test]
fn test_clear_resets_scope_chain() {
    let _g = enter_named_scope("before-clear");
    assert!(!scope_chain().is_empty());

    clear();

    assert!(scope_chain().is_empty());
}

// ══════════════════════════════════════════════════════════════
//  AttachGuard nesting tests
// ══════════════════════════════════════════════════════════════

#[test]
fn test_attach_guard_restores_on_drop() {
    let key = unique_key("attach_restore", "rid");
    register::<RequestId>(key);

    set_context(key, RequestId("outer".into()));

    {
        let snap = {
            let _scope = enter_scope();
            set_context(key, RequestId("inner".into()));
            snapshot()
        };
        let _guard = attach_snapshot(snap);
        assert_eq!(get_context::<RequestId>(key).unwrap().0, "inner");
    }

    // After guard drops, previous context restored
    assert_eq!(get_context::<RequestId>(key).unwrap().0, "outer");
}

#[test]
fn test_nested_attach_guards() {
    let key = unique_key("attach_nested", "rid");
    register::<RequestId>(key);

    set_context(key, RequestId("level-0".into()));

    let snap1 = {
        let _scope = enter_scope();
        set_context(key, RequestId("level-1".into()));
        snapshot()
    };
    let snap2 = {
        let _scope = enter_scope();
        set_context(key, RequestId("level-2".into()));
        snapshot()
    };

    {
        let _g1 = attach_snapshot(snap1);
        assert_eq!(get_context::<RequestId>(key).unwrap().0, "level-1");

        {
            let _g2 = attach_snapshot(snap2);
            assert_eq!(get_context::<RequestId>(key).unwrap().0, "level-2");
        }
        // g2 dropped — back to level-1
        assert_eq!(get_context::<RequestId>(key).unwrap().0, "level-1");
    }
    // g1 dropped — back to level-0
    assert_eq!(get_context::<RequestId>(key).unwrap().0, "level-0");
}

// ══════════════════════════════════════════════════════════════
//  Snapshot serialize/deserialize roundtrip tests
// ══════════════════════════════════════════════════════════════

#[test]
fn test_snapshot_serialize_deserialize_roundtrip() {
    let key = unique_key("snap_roundtrip", "rid");
    register::<RequestId>(key);

    set_context(key, RequestId("wire-val".into()));
    let _scope = enter_named_scope("wire-scope");

    let snap = capture();
    let bytes = snap.serialize().unwrap();
    let restored = ContextSnapshot::deserialize(&bytes).unwrap();

    let _g = attach_snapshot(restored);
    assert_eq!(get_context::<RequestId>(key).unwrap().0, "wire-val");
    assert!(scope_chain().contains(&"wire-scope".to_string()));
}

#[test]
fn test_snapshot_deserialize_invalid_bytes() {
    let result = ContextSnapshot::deserialize(&[0xFF, 0xFF, 0xFF]);
    assert!(result.is_err());
}

#[test]
fn test_snapshot_serialize_excludes_local() {
    let key_remote = unique_key("snap_ser_remote", "remote");
    let key_local = unique_key("snap_ser_local", "local");
    register::<RequestId>(key_remote);
    register_with::<RequestId>(key_local, |o| o.local_only());

    set_context(key_remote, RequestId("remote".into()));
    set_context(key_local, RequestId("local".into()));

    let snap = capture();
    let bytes = snap.serialize().unwrap();
    let restored = ContextSnapshot::deserialize(&bytes).unwrap();

    let _g = attach_snapshot(restored);
    assert_eq!(get_context::<RequestId>(key_remote).unwrap().0, "remote");
    // Local key not serialized, so not present after deserialize
    assert_eq!(get_context::<RequestId>(key_local), None);
}

// ══════════════════════════════════════════════════════════════
//  Thread safety tests
// ══════════════════════════════════════════════════════════════

#[test]
fn test_context_is_thread_isolated() {
    let key = unique_key("thread_iso", "rid");
    register::<RequestId>(key);

    set_context(key, RequestId("main-thread".into()));

    let handle = std::thread::spawn(move || {
        // Different thread has its own context
        assert_eq!(get_context::<RequestId>(key), None);
        set_context(key, RequestId("other-thread".into()));
        get_context::<RequestId>(key).unwrap()
    });

    let other_val = handle.join().unwrap();
    assert_eq!(other_val.0, "other-thread");
    // Main thread unchanged
    assert_eq!(get_context::<RequestId>(key).unwrap().0, "main-thread");
}

#[test]
fn test_snapshot_can_cross_threads() {
    let key = unique_key("snap_cross_thread", "rid");
    register::<RequestId>(key);

    set_context(key, RequestId("cross-thread".into()));
    let snap = capture();

    let handle = std::thread::spawn(move || {
        let _g = attach_snapshot(snap);
        get_context::<RequestId>(key).unwrap()
    });

    let result = handle.join().unwrap();
    assert_eq!(result.0, "cross-thread");
}