1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
//! The capability context type.
//!
//! `Cx` is the token that grants access to runtime capabilities:
//! - Querying identity (region ID, task ID)
//! - Checking cancellation status
//! - Yielding and sleeping
//! - Tracing
//!
//! # Capability Model
//!
//! All effectful operations in Asupersync flow through explicit `Cx` tokens.
//! This design prevents ambient authority and enables:
//!
//! - **Effect interception**: Production vs lab runtime can interpret effects differently
//! - **Cancellation propagation**: Cx carries cancellation signals through the task tree
//! - **Budget enforcement**: Deadlines and poll quotas flow through Cx
//! - **Observability**: Tracing and spans are tied to task identity
//!
//! # Thread Safety
//!
//! `Cx` is `Send + Sync` due to its internal `Arc<RwLock>`. However, the semantic
//! contract is that a `Cx` is associated with a specific task and should not be
//! shared across task boundaries. The runtime manages Cx lifetime and ensures
//! each task receives its own context.
//!
//! # Wrapping Cx for Frameworks
//!
//! Framework authors (e.g., fastapi_rust) should wrap `Cx` rather than store it directly:
//!
//! ```ignore
//! // CORRECT: Wrap Cx reference, delegate capabilities
//! pub struct RequestContext<'a> {
//! cx: &'a Cx,
//! request: &'a Request,
//! // framework-specific fields
//! }
//!
//! impl<'a> RequestContext<'a> {
//! pub fn check_cancelled(&self) -> bool {
//! self.cx.is_cancel_requested()
//! }
//!
//! pub fn budget(&self) -> Budget {
//! self.cx.budget()
//! }
//! }
//! ```
//!
//! This pattern ensures:
//! - Cx lifetime is tied to the request scope
//! - Framework can add domain-specific context
//! - All capabilities flow through the wrapped Cx
use super::cap;
use super::macaroon::{MacaroonToken, VerificationContext, VerificationError};
use super::registry::RegistryHandle;
use crate::combinator::select::SelectAll;
use crate::evidence_sink::EvidenceSink;
#[cfg(feature = "messaging-fabric")]
use crate::messaging::capability::{
FabricCapability, FabricCapabilityGrant, FabricCapabilityGrantError, FabricCapabilityId,
FabricCapabilityRegistry, FabricCapabilityScope, GrantedFabricToken, PublishPermit,
SubjectFamilyTag, SubscribeToken,
};
#[cfg(feature = "messaging-fabric")]
use crate::messaging::class::DeliveryClass;
#[cfg(feature = "messaging-fabric")]
use crate::messaging::ir::CapabilityTokenSchema;
#[cfg(feature = "messaging-fabric")]
use crate::messaging::subject::SubjectPattern;
use crate::observability::{
DiagnosticContext, LogCollector, LogEntry, ObservabilityConfig, SpanId,
};
use crate::remote::RemoteCap;
use crate::runtime::blocking_pool::BlockingPoolHandle;
use crate::runtime::io_driver::IoDriverHandle;
#[cfg(unix)]
use crate::runtime::io_driver::IoRegistration;
#[cfg(unix)]
use crate::runtime::reactor::{Interest, Source};
use crate::runtime::state::LoserDrainHistoryHandle;
use crate::runtime::task_handle::JoinError;
use crate::time::{TimerDriverHandle, timeout};
use crate::trace::distributed::{LogicalClockHandle, LogicalTime};
use crate::trace::{TraceBufferHandle, TraceEvent};
use crate::tracing_compat::{debug, error, info, trace, warn};
use crate::types::{
Budget, CancelKind, CancelReason, CapabilityBudget, CapabilityBudgetRefusal,
CapabilityBudgetRequirements, CxInner, RegionId, SystemPressure, TaskId, Time,
};
use crate::util::{ArenaIndex, EntropySource, OsEntropy};
use std::cell::RefCell;
use std::future::Future;
use std::marker::PhantomData;
use std::pin::Pin;
use std::sync::Arc;
#[cfg(unix)]
use std::task::Waker;
use std::time::Duration;
type NamedFuture<T> = (&'static str, Pin<Box<dyn Future<Output = T> + Send>>);
type NamedFutures<T> = Vec<NamedFuture<T>>;
/// Get the current wall clock time.
fn wall_clock_now() -> Time {
crate::time::wall_now()
}
/// Maximum allowed length of a `task_type` label value. Sized to fit the
/// dot-separated identifier conventions used by gRPC service names
/// (`package.Service.Method`) without admitting unbounded user input.
/// (br-asupersync-9vpwpc)
const MAX_TASK_TYPE_LEN: usize = 64;
/// Returns true if `s` is a syntactically safe `task_type` label.
///
/// A safe value is non-empty, ≤ [`MAX_TASK_TYPE_LEN`] bytes, starts with
/// an ASCII letter, and contains only ASCII alphanumerics plus the
/// punctuation `_`, `.`, `-`, `:`. This rejects the high-entropy shapes
/// typical of PII (UUIDs, base64 tokens, email addresses contain `@`,
/// user-id-templated formats contain `{}`, etc.) and the whitespace /
/// control characters that would corrupt OpenTelemetry label exports.
/// (br-asupersync-9vpwpc)
pub(crate) fn is_valid_task_type(s: &str) -> bool {
if s.is_empty() || s.len() > MAX_TASK_TYPE_LEN {
return false;
}
let mut bytes = s.bytes();
let first = bytes.next().expect("checked non-empty above");
if !first.is_ascii_alphabetic() {
return false;
}
bytes.all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'.' | b'-' | b':'))
}
#[cfg(unix)]
fn noop_waker() -> Waker {
Waker::noop().clone()
}
/// Grouped handle fields shared behind a single `Arc` to reduce per-clone
/// refcount operations from ~13 to 1 for this bundle.
#[derive(Debug, Clone)]
struct CxHandles {
io_driver: Option<IoDriverHandle>,
io_cap: Option<Arc<dyn crate::io::IoCap>>,
timer_driver: Option<TimerDriverHandle>,
blocking_pool: Option<BlockingPoolHandle>,
entropy: Arc<dyn EntropySource>,
logical_clock: LogicalClockHandle,
remote_cap: Option<Arc<RemoteCap>>,
registry: Option<RegistryHandle>,
pressure: Option<Arc<SystemPressure>>,
evidence_sink: Option<Arc<dyn EvidenceSink>>,
macaroon: Option<Arc<MacaroonToken>>,
#[cfg(feature = "messaging-fabric")]
fabric_capabilities: Arc<FabricCapabilityRegistry>,
}
/// The capability context for a task.
///
/// `Cx` provides access to runtime capabilities within Asupersync. All effectful
/// operations flow through `Cx`, ensuring explicit capability security with no
/// ambient authority.
///
/// # Overview
///
/// A `Cx` instance is provided to each task by the runtime. It grants access to:
///
/// - **Identity**: Query the current region and task IDs
/// - **Budget**: Check remaining time/poll quotas
/// - **Cancellation**: Observe and respond to cancellation requests
/// - **Tracing**: Emit trace events for observability
///
/// # Cloning
///
/// `Cx` is cheaply clonable (it wraps an `Arc`). Clones share the same
/// underlying state, so cancellation signals and budget updates are visible
/// to all clones.
#[derive(Debug)]
pub struct Cx<Caps = cap::All> {
pub(crate) inner: Arc<parking_lot::RwLock<CxInner>>,
observability: Arc<parking_lot::RwLock<ObservabilityState>>,
handles: Arc<CxHandles>,
/// br-asupersync-5ckssb: runtime capability mask. Mirrors the
/// type-level `Caps` parameter for cx instances obtained the
/// normal way (through the runtime / restrict / for_testing).
/// For cx instances obtained via [`Cx::current`], this mask
/// reflects the **innermost** restriction pushed onto the
/// thread-local restriction stack — so an ambient lookup
/// cannot escape a narrowing applied by an outer
/// `set_current_restricted` or `push_restriction`.
///
/// Cap-gated *Option*-returning methods (`io`, `remote`,
/// `timer_driver`, `fetch_cap`) consult this mask in addition
/// to the type-level `Caps` bound and return `None` when the
/// runtime mask blocks the capability — this is the actual
/// teeth of the ambient-authority defense.
pub(crate) runtime_mask: cap::CapMask,
// Use fn() -> Caps instead of just Caps to ensure Send+Sync regardless of Caps
_caps: PhantomData<fn() -> Caps>,
}
// Manual Clone impl to avoid requiring `Caps: Clone` (Caps is just a phantom marker type).
// Only 3 Arc increments instead of ~15.
impl<Caps> Clone for Cx<Caps> {
#[inline]
fn clone(&self) -> Self {
Self {
inner: Arc::clone(&self.inner),
observability: Arc::clone(&self.observability),
handles: Arc::clone(&self.handles),
runtime_mask: self.runtime_mask,
_caps: PhantomData,
}
}
}
/// Internal observability state shared by `Cx` clones.
#[derive(Debug, Clone)]
pub struct ObservabilityState {
collector: Option<LogCollector>,
context: DiagnosticContext,
trace: Option<TraceBufferHandle>,
loser_drain_history: Option<LoserDrainHistoryHandle>,
include_timestamps: bool,
}
impl ObservabilityState {
fn new(region: RegionId, task: TaskId) -> Self {
let context = DiagnosticContext::new()
.with_task_id(task)
.with_region_id(region)
.with_span_id(SpanId::new());
Self {
collector: None,
context,
trace: None,
loser_drain_history: None,
include_timestamps: true,
}
}
pub(crate) fn new_with_config(
region: RegionId,
task: TaskId,
config: &ObservabilityConfig,
collector: Option<LogCollector>,
) -> Self {
let context = config
.create_diagnostic_context()
.with_task_id(task)
.with_region_id(region)
.with_span_id(SpanId::new());
Self {
collector,
context,
trace: None,
loser_drain_history: None,
include_timestamps: config.include_timestamps(),
}
}
fn derive_child(&self, region: RegionId, task: TaskId) -> Self {
let mut context = self.context.clone().fork();
context = context.with_task_id(task).with_region_id(region);
Self {
collector: self.collector.clone(),
context,
trace: self.trace.clone(),
loser_drain_history: self.loser_drain_history.clone(),
include_timestamps: self.include_timestamps,
}
}
}
/// Guard that restores the cancellation mask on drop.
struct MaskGuard<'a> {
inner: &'a Arc<parking_lot::RwLock<CxInner>>,
}
impl Drop for MaskGuard<'_> {
/// Implements `inv.cancel.mask_monotone` (#12): mask_depth only decreases
/// during cancel processing. `saturating_sub` ensures no underflow.
fn drop(&mut self) {
let mut inner = self.inner.write();
inner.mask_depth = inner.mask_depth.saturating_sub(1);
}
}
type FullCx = Cx<cap::All>;
/// br-asupersync-5ckssb: a single frame on the thread-local
/// `CURRENT_CX_STACK`. Each `set_current` push records BOTH the cx
/// itself AND the runtime [`cap::CapMask`] under which it was
/// installed. `Cx::current()` walks the stack to find the innermost
/// frame and returns its cx with the frame's mask applied — so a
/// nested `set_current_restricted::<Cx<NoCaps>>(...)` makes any
/// subsequent ambient `Cx::current()` lookup observe `CapMask::none()`
/// even though the underlying inner state is shared.
#[derive(Debug, Clone)]
struct CurrentCxFrame {
cx: FullCx,
mask: cap::CapMask,
}
thread_local! {
/// Stack of `(cx, mask)` frames. The top of the stack is the
/// innermost installed context; `current()` returns from there.
/// The historical `Option<FullCx>` semantic is preserved by the
/// invariant that an empty stack means "no current cx" — i.e.
/// `current()` returns `None`.
static CURRENT_CX_STACK: RefCell<Vec<CurrentCxFrame>> = const { RefCell::new(Vec::new()) };
}
/// Guard that pops the corresponding frame from the
/// `CURRENT_CX_STACK` on drop. (br-asupersync-5ckssb)
#[cfg_attr(feature = "test-internals", visibility::make(pub))]
/// Guard returned by ambient current-context installation helpers.
pub struct CurrentCxGuard {
/// Whether this guard pushed a frame (true) or was a no-op
/// (false, when caller passed `None`). Determines whether drop
/// pops.
pushed: bool,
_not_send: std::marker::PhantomData<*mut ()>,
}
impl Drop for CurrentCxGuard {
fn drop(&mut self) {
if !self.pushed {
return;
}
let _ = CURRENT_CX_STACK.try_with(|stack| {
stack.borrow_mut().pop();
});
}
}
impl FullCx {
/// Returns the current task context, if one is set.
///
/// This is set by the runtime while polling a task.
///
/// br-asupersync-5ckssb: walks the thread-local restriction stack
/// to find the **innermost** installed context. If an outer scope
/// pushed a restricted cx (via [`Cx::set_current_restricted`] or
/// [`Cx::push_restriction`]), the returned cx carries the
/// narrowed runtime mask, so cap-gated *Option*-returning
/// methods (`io`, `remote`, `timer_driver`, `fetch_cap`) return
/// `None` for any capability blocked by the restriction. This
/// closes the ambient-authority leak that previously let
/// untrusted call sites obtain a full-cap cx via the ambient
/// lookup regardless of the type-level `Caps` parameter on the
/// cx they were given as a function argument.
///
/// Returns `None` when no task context is installed and also during
/// thread-local teardown, where the ambient context is no longer
/// accessible.
#[inline]
#[must_use]
pub fn current() -> Option<Self> {
CURRENT_CX_STACK
.try_with(|slot| {
slot.borrow().last().map(|frame| {
let mut cx = frame.cx.clone();
cx.runtime_mask = frame.mask;
cx
})
})
.unwrap_or(None)
}
/// Returns `true` iff a task context is installed on the current
/// thread, without cloning any of the cx's internal `Arc`s.
///
/// br-asupersync-xqt7dj: zero-Arc-clone existence check. Equivalent
/// to `Cx::current().is_some()` but avoids the 3 atomic ops on the
/// strong-count fields (inner, observability, handles) that
/// `Cx::current` performs to materialize a returnable owned value.
/// Use this for tight async polls that only need to detect whether
/// they are running under a task context (e.g., diagnostic hooks).
#[inline]
#[must_use]
pub fn is_active() -> bool {
CURRENT_CX_STACK
.try_with(|slot| !slot.borrow().is_empty())
.unwrap_or(false)
}
/// Borrows the current task context for the duration of the closure.
///
/// br-asupersync-xqt7dj — zero-Arc-clone hot path for callers that
/// only need to *read* from the active context (`checkpoint()`,
/// `trace()`, `now()`, `has_io()`, etc.). The legacy
/// [`Cx::current`] clones the three internal `Arc`s (3 atomic ops
/// per call) so the returned cx can be retained across await
/// points; for hot async loops that consult the ambient context
/// many times per poll, that clone cost compounds.
///
/// `with_current` saves all 3 atomic ops in the common case (no
/// active `set_current_restricted` / `push_restriction` narrowing
/// — i.e. `frame.mask == frame.cx.runtime_mask`), borrowing the
/// frame's `Cx` directly and handing `&Cx` to the closure. When a
/// restriction stack IS active and the frame's mask differs from
/// the cx's runtime mask, we must apply the narrowed mask to a
/// stack-local copy of the cx (1 cheap clone) so cap-gated
/// `Option`-returning methods (`io`, `remote`, `timer_driver`,
/// `fetch_cap`) observe the restriction; that case degrades to the
/// same cost as legacy `current()`, never worse.
///
/// **Lifetime semantics:** the borrow on `CURRENT_CX_STACK` is
/// held for the entire closure body, so the closure cannot install
/// a new ambient cx via `set_current*` (the inner mutable borrow
/// would panic). Use [`Cx::current`] (which clones) when the
/// ambient cx must outlive a single read or be moved into an
/// async block.
///
/// **Restriction-mask correctness:** the borrowed/cloned cx
/// observes the active frame's mask, so callers running under a
/// `set_current_restricted` scope see the narrowed cap view via
/// `with_current` exactly as they would via `current().clone()`.
///
/// Returns `None` when no ambient context is installed (or during
/// thread-local teardown); the closure is then NOT invoked.
#[inline]
pub fn with_current<F, R>(f: F) -> Option<R>
where
F: FnOnce(&Self) -> R,
{
CURRENT_CX_STACK
.try_with(|slot| {
let stack = slot.borrow();
let frame = stack.last()?;
if frame.mask == frame.cx.runtime_mask {
// Common case: no restriction-stack narrowing. The
// borrowed frame.cx already carries the correct
// runtime mask, so we hand it to the closure
// without any Arc::clone — saves 3 atomic ops
// versus `Cx::current()`.
Some(f(&frame.cx))
} else {
// Restricted: apply the frame's narrowed mask to a
// stack-local copy. Equivalent in cost to legacy
// `current()` (3 Arc::clone), so the worst case is
// a tie, never a regression.
let mut cx = frame.cx.clone();
cx.runtime_mask = frame.mask;
Some(f(&cx))
}
})
.ok()
.flatten()
}
/// Sets the current task context for the duration of the guard.
///
/// Pushes a new frame onto the thread-local stack with the FULL
/// capability mask. For installations that should narrow the
/// ambient view (e.g. when handing control to untrusted code
/// that should not see full caps), use
/// [`Cx::set_current_restricted`] instead.
#[inline]
#[must_use]
#[cfg_attr(feature = "test-internals", visibility::make(pub))]
pub(crate) fn set_current(cx: Option<Self>) -> CurrentCxGuard {
let pushed = CURRENT_CX_STACK.with(|stack| match cx {
Some(cx) => {
stack.borrow_mut().push(CurrentCxFrame {
cx,
mask: cap::CapMask::all(),
});
true
}
None => false,
});
CurrentCxGuard {
pushed,
_not_send: std::marker::PhantomData,
}
}
}
impl<Caps> Cx<Caps>
where
Caps: cap::CapSetRuntimeMask,
{
/// Push this cx onto the thread-local restriction stack with
/// its OWN runtime mask (computed from the type-level `Caps`
/// parameter). While the returned guard is alive, any ambient
/// `Cx::current()` lookup observes the narrowed mask — even if
/// the underlying `FullCx` it wraps has every capability bit
/// set internally.
///
/// br-asupersync-5ckssb: this is the tooling that gives the
/// `Cx::current()` ambient defense its teeth. A function that
/// is about to delegate to less-trusted code can do
///
/// ```ignore
/// let _guard = restricted_cx.set_current_restricted();
/// untrusted::do_work(); // ambient Cx::current() observes the
/// // restricted cap mask
/// ```
///
/// and be confident that the callee cannot escape its capability
/// budget via a thread-local lookup.
#[inline]
#[must_use]
pub fn set_current_restricted(self) -> CurrentCxGuard {
let mask = <Caps as cap::CapSetRuntimeMask>::MASK;
let cx = self.retype::<cap::All>();
CURRENT_CX_STACK.with(|stack| {
let mut s = stack.borrow_mut();
assert!(
s.len() < crate::types::task_context::MAX_CONTEXT_STACK_DEPTH,
"context stack depth exceeded MAX_CONTEXT_STACK_DEPTH ({}): this prevents \
stack overflow in pathological nesting scenarios. Consider reducing \
nesting depth or restructuring the code to avoid excessive context \
restriction nesting.",
crate::types::task_context::MAX_CONTEXT_STACK_DEPTH
);
s.push(CurrentCxFrame { cx, mask });
});
CurrentCxGuard {
pushed: true,
_not_send: std::marker::PhantomData,
}
}
}
impl FullCx {
/// Push an explicit [`cap::CapMask`] restriction onto the
/// thread-local stack without changing the underlying cx.
///
/// The mask is intersected with the currently-active mask
/// (whatever `Cx::current()` would otherwise return). While the
/// guard is alive, ambient lookups observe the narrowed view.
/// Useful for short scoped restrictions ("disable IO across
/// this callback") without requiring a separate restricted-cap
/// cx instance.
///
/// (br-asupersync-5ckssb)
#[must_use]
pub fn push_restriction(mask: cap::CapMask) -> CurrentCxGuard {
let pushed = CURRENT_CX_STACK.with(|stack| {
let mut s = stack.borrow_mut();
// Check depth limit before attempting to push
assert!(
s.len() < crate::types::task_context::MAX_CONTEXT_STACK_DEPTH,
"context stack depth exceeded MAX_CONTEXT_STACK_DEPTH ({}): this prevents \
stack overflow in pathological nesting scenarios. Consider reducing \
nesting depth or restructuring the code to avoid excessive context \
restriction nesting.",
crate::types::task_context::MAX_CONTEXT_STACK_DEPTH
);
// Intersect with the current top so a push can only
// ever narrow, never widen.
let (cx, intersected_mask) = match s.last() {
Some(top) => (top.cx.clone(), top.mask.intersect(mask)),
// No installed cx: push a no-op marker that current()
// will see as None (no cx to clone). Skip push since
// there's nothing to restrict.
None => return false,
};
s.push(CurrentCxFrame {
cx,
mask: intersected_mask,
});
true
});
CurrentCxGuard {
pushed,
_not_send: std::marker::PhantomData,
}
}
}
impl<Caps> Cx<Caps> {
/// Creates a new capability context (internal use).
#[must_use]
#[allow(dead_code)]
#[cfg_attr(feature = "test-internals", visibility::make(pub))]
pub(crate) fn new(region: RegionId, task: TaskId, budget: Budget) -> Self {
Self::new_with_observability(region, task, budget, None, None, None)
}
/// Creates a new capability context from shared state (internal use).
#[allow(dead_code)] // Internal construction path for runtime integration
pub(crate) fn from_inner(inner: Arc<parking_lot::RwLock<CxInner>>) -> Self {
let (region, task) = {
let guard = inner.read();
(guard.region, guard.task)
};
Self {
inner,
observability: Arc::new(parking_lot::RwLock::new(ObservabilityState::new(
region, task,
))),
handles: Arc::new(CxHandles {
io_driver: None,
io_cap: None,
timer_driver: None,
blocking_pool: None,
entropy: Arc::new(OsEntropy),
logical_clock: LogicalClockHandle::default(),
remote_cap: None,
registry: None,
pressure: None,
evidence_sink: None,
macaroon: None,
#[cfg(feature = "messaging-fabric")]
fabric_capabilities: Arc::new(FabricCapabilityRegistry::default()),
}),
runtime_mask: cap::CapMask::all(),
_caps: PhantomData,
}
}
/// Creates a new capability context with optional observability state (internal use).
#[must_use]
#[cfg_attr(feature = "test-internals", visibility::make(pub))]
pub(crate) fn new_with_observability(
region: RegionId,
task: TaskId,
budget: Budget,
observability: Option<ObservabilityState>,
io_driver: Option<IoDriverHandle>,
entropy: Option<Arc<dyn EntropySource>>,
) -> Self {
Self::new_with_io(
region,
task,
budget,
observability,
io_driver,
None,
entropy,
)
}
/// Creates a new capability context with optional I/O capability (internal use).
#[must_use]
#[cfg_attr(feature = "test-internals", visibility::make(pub))]
pub(crate) fn new_with_io(
region: RegionId,
task: TaskId,
budget: Budget,
observability: Option<ObservabilityState>,
io_driver: Option<IoDriverHandle>,
io_cap: Option<Arc<dyn crate::io::IoCap>>,
entropy: Option<Arc<dyn EntropySource>>,
) -> Self {
Self::new_with_drivers(
region,
task,
budget,
observability,
io_driver,
io_cap,
None,
entropy,
)
}
/// Creates a new capability context with optional I/O and timer drivers (internal use).
#[must_use]
#[cfg_attr(feature = "test-internals", visibility::make(pub))]
#[allow(clippy::too_many_arguments)]
pub(crate) fn new_with_drivers(
region: RegionId,
task: TaskId,
budget: Budget,
observability: Option<ObservabilityState>,
io_driver: Option<IoDriverHandle>,
io_cap: Option<Arc<dyn crate::io::IoCap>>,
timer_driver: Option<TimerDriverHandle>,
entropy: Option<Arc<dyn EntropySource>>,
) -> Self {
let inner = Arc::new(parking_lot::RwLock::new(CxInner::new(region, task, budget)));
let observability_state =
observability.unwrap_or_else(|| ObservabilityState::new(region, task));
let observability = Arc::new(parking_lot::RwLock::new(observability_state));
let entropy = entropy.unwrap_or_else(|| Arc::new(OsEntropy));
debug!(
task_id = ?task,
region_id = ?region,
budget_deadline = ?budget.deadline,
budget_poll_quota = budget.poll_quota,
budget_cost_quota = ?budget.cost_quota,
budget_priority = budget.priority,
budget_source = "cx_new",
"budget initialized for context"
);
Self {
inner,
observability,
handles: Arc::new(CxHandles {
io_driver,
io_cap,
timer_driver,
blocking_pool: None,
entropy,
logical_clock: LogicalClockHandle::default(),
remote_cap: None,
registry: None,
pressure: None,
evidence_sink: None,
macaroon: None,
#[cfg(feature = "messaging-fabric")]
fabric_capabilities: Arc::new(FabricCapabilityRegistry::default()),
}),
runtime_mask: cap::CapMask::all(),
_caps: PhantomData,
}
}
/// Returns a cloned handle to the I/O driver, if present.
#[inline]
#[must_use]
pub(crate) fn io_driver_handle(&self) -> Option<IoDriverHandle> {
self.handles.io_driver.clone()
}
/// Returns a cloned handle to the blocking pool, if present.
#[inline]
#[must_use]
pub(crate) fn blocking_pool_handle(&self) -> Option<BlockingPoolHandle> {
self.handles.blocking_pool.clone()
}
/// Attaches a blocking pool handle to this context.
#[must_use]
pub(crate) fn with_blocking_pool_handle(mut self, handle: Option<BlockingPoolHandle>) -> Self {
Arc::make_mut(&mut self.handles).blocking_pool = handle;
self
}
/// Attaches a logical clock handle to this context.
#[must_use]
pub(crate) fn with_logical_clock(mut self, clock: LogicalClockHandle) -> Self {
Arc::make_mut(&mut self.handles).logical_clock = clock;
self
}
/// Re-type this context to a narrower capability set.
///
/// This is a zero-cost type-level restriction. It does not change runtime behavior,
/// but removes access to gated APIs at compile time.
#[must_use]
pub fn restrict<NewCaps>(&self) -> Cx<NewCaps>
where
NewCaps: cap::SubsetOf<Caps>,
{
self.retype()
}
/// Internal re-typing helper (no subset enforcement).
#[inline]
#[must_use]
pub(crate) fn retype<NewCaps>(&self) -> Cx<NewCaps> {
Cx {
inner: self.inner.clone(),
observability: self.observability.clone(),
handles: self.handles.clone(),
// br-asupersync-5ckssb: preserve the runtime mask across
// retype. Narrowing the type-level Caps does NOT widen
// the runtime mask; widening is impossible at this layer
// because the typed `restrict` requires SubsetOf.
runtime_mask: self.runtime_mask,
_caps: PhantomData,
}
}
/// Attaches a registry handle to this context.
///
/// This is how Spork-style naming is made capability-scoped (no globals):
/// tasks only see a registry if their `Cx` carries one.
#[must_use]
pub(crate) fn with_registry_handle(mut self, registry: Option<RegistryHandle>) -> Self {
Arc::make_mut(&mut self.handles).registry = registry;
self
}
/// Attaches a remote capability to this context.
///
/// This allows the context to perform remote operations like `spawn_remote`.
#[must_use]
pub fn with_remote_cap(mut self, cap: RemoteCap) -> Self {
Arc::make_mut(&mut self.handles).remote_cap = Some(Arc::new(cap));
self
}
/// Attach a system pressure handle for compute budget propagation.
///
/// The handle is shared via `Arc` so all clones observe the same pressure
/// state. A monitor thread can call [`SystemPressure::set_headroom`] to
/// update the value, and any code with `&Cx` can read it lock-free.
#[must_use]
pub fn with_pressure(mut self, pressure: Arc<SystemPressure>) -> Self {
Arc::make_mut(&mut self.handles).pressure = Some(pressure);
self
}
/// Read the current system pressure, if attached.
///
/// Returns `None` if no pressure handle was attached to this context.
#[must_use]
#[inline]
pub fn pressure(&self) -> Option<&SystemPressure> {
self.handles.pressure.as_deref()
}
/// Returns a cloned handle to the configured system pressure source, if any.
///
/// This is `pub(crate)` so spawned child tasks can inherit the same shared
/// pressure state as their parent. Some build slices currently exercise
/// the inheritance path only behind optional runtime wiring/tests.
#[allow(dead_code)]
#[must_use]
pub(crate) fn pressure_handle(&self) -> Option<Arc<SystemPressure>> {
self.handles.pressure.clone()
}
/// Returns a cloned handle to the configured remote capability, if any.
///
/// This is `pub(crate)` so internal wiring (e.g. spawning child tasks) can
/// inherit remote capability without requiring `Caps: HasRemote` bounds.
#[inline]
#[must_use]
pub(crate) fn remote_cap_handle(&self) -> Option<Arc<RemoteCap>> {
self.handles.remote_cap.clone()
}
/// Attaches an already-shared remote capability handle to this context.
///
/// This is the internal counterpart to [`Cx::with_remote_cap`] used for
/// capability propagation to child contexts.
#[must_use]
pub(crate) fn with_remote_cap_handle(mut self, cap: Option<Arc<RemoteCap>>) -> Self {
Arc::make_mut(&mut self.handles).remote_cap = cap;
self
}
/// Returns the registry capability handle, if attached.
#[inline]
#[must_use]
pub fn registry_handle(&self) -> Option<RegistryHandle> {
self.handles.registry.clone()
}
/// Returns true if a registry handle is attached.
#[inline]
#[must_use]
pub fn has_registry(&self) -> bool {
self.handles.registry.is_some()
}
/// Grant a shared FABRIC capability for runtime and distributed-path checks.
#[cfg(feature = "messaging-fabric")]
pub fn grant_fabric_capability(
&self,
capability: FabricCapability,
) -> Result<FabricCapabilityGrant, FabricCapabilityGrantError> {
self.handles.fabric_capabilities.grant(capability)
}
/// Return the current FABRIC capability grants attached to this context.
#[cfg(feature = "messaging-fabric")]
#[must_use]
pub fn fabric_capabilities(&self) -> Vec<FabricCapabilityGrant> {
self.handles.fabric_capabilities.snapshot()
}
/// Grant a publish capability and mint the corresponding linear token.
#[cfg(feature = "messaging-fabric")]
pub fn grant_publish_capability<S: SubjectFamilyTag>(
&self,
subject: SubjectPattern,
schema: &CapabilityTokenSchema,
delivery_class: DeliveryClass,
) -> Result<GrantedFabricToken<PublishPermit<S>>, FabricCapabilityGrantError> {
let token = PublishPermit::<S>::authorize(schema, delivery_class)?;
let grant = self.grant_fabric_capability(FabricCapability::Publish { subject })?;
Ok(GrantedFabricToken::new(grant, token))
}
/// Grant a subscription capability and mint the corresponding linear token.
#[cfg(feature = "messaging-fabric")]
pub fn grant_subscribe_capability<S: SubjectFamilyTag>(
&self,
subject: SubjectPattern,
schema: &CapabilityTokenSchema,
delivery_class: DeliveryClass,
) -> Result<GrantedFabricToken<SubscribeToken<S>>, FabricCapabilityGrantError> {
let token = SubscribeToken::<S>::authorize(schema, delivery_class)?;
let grant = self.grant_fabric_capability(FabricCapability::Subscribe { subject })?;
Ok(GrantedFabricToken::new(grant, token))
}
/// Return true when the requested FABRIC capability is currently attached.
#[cfg(feature = "messaging-fabric")]
#[must_use]
pub fn check_fabric_capability(&self, capability: &FabricCapability) -> bool {
self.handles.fabric_capabilities.check(capability)
}
/// Revoke one FABRIC capability by its stable grant identifier.
#[cfg(feature = "messaging-fabric")]
#[must_use]
pub fn revoke_fabric_capability(&self, id: FabricCapabilityId) -> Option<FabricCapability> {
self.handles.fabric_capabilities.revoke_by_id(id)
}
/// Revoke every FABRIC capability whose subject space overlaps `subject`.
#[cfg(feature = "messaging-fabric")]
#[must_use]
pub fn revoke_fabric_capability_by_subject(&self, subject: &SubjectPattern) -> usize {
self.handles.fabric_capabilities.revoke_by_subject(subject)
}
/// Revoke every FABRIC capability in the provided coarse scope.
#[cfg(feature = "messaging-fabric")]
#[must_use]
pub fn revoke_fabric_capability_scope(&self, scope: FabricCapabilityScope) -> usize {
self.handles.fabric_capabilities.revoke_scope(scope)
}
/// Attaches an evidence sink for runtime decision tracing.
#[must_use]
pub fn with_evidence_sink(mut self, sink: Option<Arc<dyn EvidenceSink>>) -> Self {
Arc::make_mut(&mut self.handles).evidence_sink = sink;
self
}
/// Returns a cloned handle to the evidence sink, if attached.
#[inline]
#[must_use]
pub(crate) fn evidence_sink_handle(&self) -> Option<Arc<dyn EvidenceSink>> {
self.handles.evidence_sink.clone()
}
/// Emit an evidence entry to the attached sink, if any.
///
/// This is a no-op if no evidence sink is configured. Errors during
/// emission are handled internally by the sink (logged and dropped).
pub fn emit_evidence(&self, entry: &franken_evidence::EvidenceLedger) {
if let Some(ref sink) = self.handles.evidence_sink {
sink.emit(entry);
}
}
// -----------------------------------------------------------------
// Macaroon-based capability attenuation (bd-2lqyk.2)
// -----------------------------------------------------------------
/// Attaches a Macaroon capability token to this context.
///
/// The token is stored in an `Arc` for cheap cloning. Child contexts
/// created via [`restrict`](Self::restrict) or [`retype`](Self::retype)
/// inherit the macaroon.
#[must_use]
pub fn with_macaroon(mut self, token: MacaroonToken) -> Self {
Arc::make_mut(&mut self.handles).macaroon = Some(Arc::new(token));
self
}
/// Attaches a pre-shared Macaroon handle to this context (internal use).
#[must_use]
#[allow(dead_code)] // Macaroon integration API
pub(crate) fn with_macaroon_handle(mut self, handle: Option<Arc<MacaroonToken>>) -> Self {
Arc::make_mut(&mut self.handles).macaroon = handle;
self
}
/// Returns a reference to the attached Macaroon token, if any.
#[inline]
#[must_use]
pub fn macaroon(&self) -> Option<&MacaroonToken> {
self.handles.macaroon.as_deref()
}
/// Returns a cloned `Arc` handle to the macaroon, if any.
#[inline]
#[must_use]
#[allow(dead_code)] // Macaroon integration API
pub(crate) fn macaroon_handle(&self) -> Option<Arc<MacaroonToken>> {
self.handles.macaroon.clone()
}
/// Attenuate the capability token by adding a caveat.
///
/// Returns a new `Cx` with an attenuated macaroon. The original
/// context is unchanged. This does **not** require the root key —
/// any holder can add caveats (but nobody can remove them).
///
/// Returns `None` if no macaroon is attached or the caveat cannot be
/// encoded in the macaroon wire format.
#[must_use]
pub fn attenuate(&self, predicate: super::macaroon::CaveatPredicate) -> Option<Self> {
let token = self.handles.macaroon.as_ref()?;
if let Err(_error) = predicate.validate() {
error!(
token_id = %token.identifier(),
error = %_error,
"macaroon attenuation rejected unencodable caveat"
);
return None;
}
let attenuated = MacaroonToken::clone(token).add_caveat(predicate.clone());
if !attenuated.is_direct_attenuation_of(token, &predicate) {
error!(
token_id = %token.identifier(),
"macaroon attenuation failed runtime subset validation"
);
return None;
}
info!(
token_id = %attenuated.identifier(),
caveat_count = attenuated.caveat_count(),
"capability attenuated"
);
let mut cx = self.clone();
Arc::make_mut(&mut cx.handles).macaroon = Some(Arc::new(attenuated));
Some(cx)
}
/// Attenuate with a time limit: the token expires at `deadline_ms`.
///
/// Convenience wrapper around [`attenuate`](Self::attenuate) with
/// [`CaveatPredicate::TimeBefore`].
///
/// Returns `None` if no macaroon is attached.
#[must_use]
pub fn attenuate_time_limit(&self, deadline_ms: u64) -> Option<Self> {
self.attenuate(super::macaroon::CaveatPredicate::TimeBefore(deadline_ms))
}
/// Attenuate with a resource scope restriction.
///
/// The `pattern` uses simple glob syntax: `*` matches any single segment,
/// `**` matches any number of segments.
///
/// Returns `None` if no macaroon is attached or `pattern` exceeds the
/// macaroon wire-format length cap.
#[must_use]
pub fn attenuate_scope(&self, pattern: impl Into<String>) -> Option<Self> {
self.attenuate(super::macaroon::CaveatPredicate::ResourceScope(
pattern.into(),
))
}
/// Attenuate with a windowed rate limit.
///
/// Restricts the token to at most `max_count` uses per `window_secs`.
/// The caller is responsible for tracking the sliding window and
/// providing both the observed window duration and use count in
/// [`VerificationContext`].
///
/// Returns `None` if no macaroon is attached.
#[must_use]
pub fn attenuate_rate_limit(&self, max_count: u32, window_secs: u32) -> Option<Self> {
self.attenuate(super::macaroon::CaveatPredicate::RateLimit {
max_count,
window_secs,
})
}
/// Attenuate with the Cx's current budget deadline.
///
/// If the Cx has a finite deadline, adds a `TimeBefore` caveat using it.
/// If no deadline is set, the macaroon is returned unchanged.
///
/// Returns `None` if no macaroon is attached.
#[must_use]
pub fn attenuate_from_budget(&self) -> Option<Self> {
let _ = self.handles.macaroon.as_ref()?;
let budget = self.budget();
budget.deadline.map_or_else(
|| Some(self.clone()),
|d| self.attenuate_time_limit(d.as_millis()),
)
}
/// Verify the attached capability token against a root key, expected
/// capability identifier, and runtime context.
///
/// Checks the HMAC chain integrity and evaluates all caveat predicates.
/// Emits evidence to the attached sink on both success and failure.
///
/// Returns `Ok(())` if the token is valid and all caveats pass.
///
/// # Errors
///
/// Returns `VerificationError` if verification fails (bad signature or
/// failed caveat). Returns `Err(VerificationError::InvalidSignature)` if
/// no macaroon is attached.
pub fn verify_capability(
&self,
root_key: &crate::security::key::AuthKey,
expected_identifier: &str,
context: &VerificationContext,
) -> Result<(), VerificationError> {
let Some(token) = self.handles.macaroon.as_ref() else {
// Emit evidence for the no-macaroon rejection before returning.
warn!(
task_id = ?self.task_id(),
region_id = ?self.region_id(),
"capability verification failed: no macaroon attached"
);
return Err(VerificationError::InvalidSignature);
};
let result = token.verify_for_identifier(root_key, expected_identifier, context);
// Emit evidence for the verification decision.
self.emit_macaroon_evidence(token, &result);
match &result {
Ok(()) => {
info!(
token_id = %token.identifier(),
caveats_checked = token.caveat_count(),
"macaroon verified successfully"
);
}
Err(VerificationError::InvalidSignature) => {
error!(
token_id = %token.identifier(),
"HMAC chain integrity violation — possible tampering"
);
}
#[allow(unused_variables)]
Err(VerificationError::UnexpectedIdentifier { expected, actual }) => {
error!(
token_id = %token.identifier(),
expected = %expected,
actual = %actual,
"macaroon identifier mismatch"
);
}
#[allow(unused_variables)]
Err(VerificationError::CaveatFailed {
index,
predicate,
reason,
}) => {
info!(
token_id = %token.identifier(),
failed_at_caveat = index,
predicate = %predicate,
reason = %reason,
"macaroon verification failed"
);
}
#[allow(unused_variables)]
Err(VerificationError::MissingDischarge { index, identifier }) => {
info!(
token_id = %token.identifier(),
failed_at_caveat = index,
discharge_id = %identifier,
"missing discharge macaroon"
);
}
#[allow(unused_variables)]
Err(VerificationError::DischargeInvalid { index, identifier }) => {
info!(
token_id = %token.identifier(),
failed_at_caveat = index,
discharge_id = %identifier,
"discharge macaroon verification failed"
);
}
#[allow(unused_variables)]
Err(VerificationError::DischargeChainTooDeep { depth }) => {
info!(
token_id = %token.identifier(),
depth = %depth,
"discharge macaroon chain too deep"
);
}
Err(VerificationError::WeakCaveatKey) => {
error!(
token_id = %token.identifier(),
"caveat key failed entropy validation — possible weak key attack"
);
}
}
result
}
/// Emit evidence for a macaroon verification decision.
fn emit_macaroon_evidence(
&self,
token: &MacaroonToken,
result: &Result<(), VerificationError>,
) {
let Some(ref sink) = self.handles.evidence_sink else {
return;
};
let now_ms = wall_clock_now().as_millis();
let (action, loss) = match result {
Ok(()) => ("verify_success".to_string(), 0.0),
Err(VerificationError::InvalidSignature) => ("verify_fail_signature".to_string(), 1.0),
Err(VerificationError::UnexpectedIdentifier { .. }) => {
("verify_fail_identifier".to_string(), 1.0)
}
Err(VerificationError::CaveatFailed { index, .. }) => {
(format!("verify_fail_caveat_{index}"), 0.5)
}
Err(VerificationError::MissingDischarge { index, .. }) => {
(format!("verify_fail_missing_discharge_{index}"), 0.8)
}
Err(VerificationError::DischargeInvalid { index, .. }) => {
(format!("verify_fail_discharge_invalid_{index}"), 0.9)
}
Err(VerificationError::DischargeChainTooDeep { depth }) => {
(format!("verify_fail_discharge_chain_too_deep_{depth}"), 1.0)
}
Err(VerificationError::WeakCaveatKey) => {
("verify_fail_weak_caveat_key".to_string(), 1.0)
}
};
let entry = franken_evidence::EvidenceLedger {
ts_unix_ms: now_ms,
component: "cx_macaroon".to_string(),
action: action.clone(),
posterior: vec![1.0],
expected_loss_by_action: std::collections::BTreeMap::from([(action, loss)]),
chosen_expected_loss: loss,
calibration_score: 1.0,
fallback_active: false,
#[allow(clippy::cast_precision_loss)]
top_features: vec![("caveat_count".to_string(), token.caveat_count() as f64)],
};
sink.emit(&entry);
}
/// Returns the current logical time without ticking.
#[inline]
#[must_use]
pub fn logical_now(&self) -> LogicalTime {
self.handles.logical_clock.now()
}
/// Returns a clone of the task's logical clock handle.
#[inline]
#[must_use]
pub(crate) fn logical_clock_handle(&self) -> LogicalClockHandle {
self.handles.logical_clock.clone()
}
/// Records a local logical event and returns the updated time.
#[inline]
#[must_use]
pub fn logical_tick(&self) -> LogicalTime {
self.handles.logical_clock.tick()
}
/// Merges a received logical time and returns the updated time.
#[inline]
#[must_use]
pub fn logical_receive(&self, sender_time: &LogicalTime) -> LogicalTime {
self.handles.logical_clock.receive(sender_time)
}
/// Returns a cloned handle to the timer driver, if present.
///
/// The timer driver provides access to timer registration for async time
/// operations like `sleep`, `timeout`, and `interval`. When present, these
/// operations use the runtime's timer wheel instead of spawning threads.
///
/// # Example
///
/// ```ignore
/// if let Some(timer) = Cx::current().and_then(|cx| cx.timer_driver()) {
/// let deadline = timer.now() + Duration::from_secs(1);
/// let handle = timer.register(deadline, waker);
/// }
/// ```
#[inline]
#[must_use]
pub fn timer_driver(&self) -> Option<TimerDriverHandle>
where
Caps: cap::HasTime,
{
// br-asupersync-5ckssb: respect the runtime mask. A cx
// obtained via Cx::current() under an outer
// set_current_restricted/push_restriction that excludes TIME
// returns None even though Caps: HasTime would otherwise
// permit access.
if !self.runtime_mask.has(cap::CapMask::TIME) {
return None;
}
self.handles.timer_driver.clone()
}
/// Returns true if a timer driver is available.
///
/// When true, time operations can use the runtime's timer wheel.
/// When false, time operations fall back to OS-level timing.
#[inline]
#[must_use]
pub fn has_timer(&self) -> bool
where
Caps: cap::HasTime,
{
self.handles.timer_driver.is_some()
}
/// Returns the I/O capability, if one is configured.
///
/// The I/O capability provides access to async I/O operations. If no capability
/// is configured, this returns `None` and I/O operations are not available.
///
/// # Capability Model
///
/// Asupersync uses explicit capability-based I/O:
/// - Production runtime configures real I/O capability (via reactor)
/// - Lab runtime can configure virtual I/O for deterministic testing
/// - Code that needs I/O must explicitly check for and use this capability
///
/// # Example
///
/// ```ignore
/// async fn read_data(cx: &Cx) -> io::Result<Vec<u8>> {
/// let io = cx.io().ok_or_else(|| {
/// io::Error::new(io::ErrorKind::Unsupported, "I/O not available")
/// })?;
///
/// // Use io capability...
/// Ok(vec![])
/// }
/// ```
#[inline]
#[must_use]
pub fn io(&self) -> Option<&dyn crate::io::IoCap>
where
Caps: cap::HasIo,
{
// br-asupersync-5ckssb: respect the runtime mask — see the
// doc-comment on `runtime_mask`. A cx obtained via
// Cx::current() under an outer restriction returns None for
// I/O even though Caps: HasIo would otherwise permit it.
if !self.runtime_mask.has(cap::CapMask::IO) {
return None;
}
self.handles.io_cap.as_ref().map(AsRef::as_ref)
}
/// Returns a cloned handle to the configured I/O capability, if any.
///
/// This is `pub(crate)` so internal wiring can preserve I/O authority when
/// deriving child task contexts without requiring `Caps: HasIo` bounds.
/// Some build slices currently exercise the inheritance path only behind
/// optional runtime wiring/tests.
#[inline]
#[allow(dead_code)]
#[must_use]
pub(crate) fn io_cap_handle(&self) -> Option<Arc<dyn crate::io::IoCap>> {
self.handles.io_cap.clone()
}
/// Returns true if I/O capability is available.
///
/// Convenience method to check if I/O operations can be performed.
#[inline]
#[must_use]
pub fn has_io(&self) -> bool
where
Caps: cap::HasIo,
{
self.handles.io_cap.is_some()
}
/// Returns the fetch adapter capability, if one is configured.
///
/// This is the browser-facing network authority surface. When present,
/// requests must pass explicit origin/method/credential policy checks
/// before any host fetch operation is attempted.
#[inline]
#[must_use]
pub fn fetch_cap(&self) -> Option<&dyn crate::io::FetchIoCap>
where
Caps: cap::HasIo,
{
// br-asupersync-5ckssb: fetch_cap is on the IO surface; gate
// it on the runtime IO bit too.
if !self.runtime_mask.has(cap::CapMask::IO) {
return None;
}
self.handles.io_cap.as_ref().and_then(|cap| cap.fetch_cap())
}
/// Returns true if a fetch adapter capability is available.
#[inline]
#[must_use]
pub fn has_fetch_cap(&self) -> bool
where
Caps: cap::HasIo,
{
self.fetch_cap().is_some()
}
/// Returns the remote capability, if one is configured.
///
/// The remote capability authorizes spawning tasks on remote nodes.
/// Without this capability, [`spawn_remote`](crate::remote::spawn_remote)
/// returns [`RemoteError::NoCapability`](crate::remote::RemoteError::NoCapability).
///
/// # Capability Model
///
/// Remote execution is an explicit capability:
/// - Production runtime configures remote capability with transport config
/// - Lab runtime can configure it for deterministic distributed testing
/// - Code that needs remote spawning must check for this capability
#[inline]
#[must_use]
pub fn remote(&self) -> Option<&RemoteCap>
where
Caps: cap::HasRemote,
{
// br-asupersync-5ckssb: respect the runtime mask. A cx
// obtained via Cx::current() under an outer restriction
// returns None for remote even though Caps: HasRemote would
// otherwise permit access — closes the ambient-lookup
// escape for the most-sensitive capability surface.
if !self.runtime_mask.has(cap::CapMask::REMOTE) {
return None;
}
self.handles.remote_cap.as_ref().map(AsRef::as_ref)
}
/// Returns true if the remote capability is available.
///
/// Convenience method to check if remote task operations can be performed.
#[inline]
#[must_use]
pub fn has_remote(&self) -> bool
where
Caps: cap::HasRemote,
{
self.runtime_mask.has(cap::CapMask::REMOTE) && self.handles.remote_cap.is_some()
}
/// Registers an I/O source with the reactor for the given interest.
///
/// This method registers a source (such as a socket or file descriptor) with
/// the reactor so that the task can be woken when I/O operations are ready.
///
/// # Arguments
///
/// * `source` - The I/O source to register (must implement [`Source`])
/// * `interest` - The I/O operations to monitor for (read, write, or both)
///
/// # Returns
///
/// Returns a [`IoRegistration`] handle that represents the active registration.
/// When dropped, the registration is automatically deregistered from the reactor.
///
/// # Errors
///
/// Returns an error if:
/// - No reactor is available (reactor not initialized or not present)
/// - The reactor fails to register the source
///
#[cfg(unix)]
pub fn register_io<S: Source>(
&self,
source: &S,
interest: Interest,
) -> std::io::Result<IoRegistration>
where
Caps: cap::HasIo,
{
let Some(driver) = self.io_driver_handle() else {
return Err(std::io::Error::new(
std::io::ErrorKind::NotConnected,
"I/O driver not available",
));
};
driver.register(source, interest, noop_waker())
}
/// Returns the current region ID.
///
/// The region ID identifies the structured concurrency scope that owns this task.
/// Useful for debugging and for associating task-specific data with region boundaries.
///
/// # Example
///
/// ```ignore
/// fn log_context(cx: &Cx) {
/// println!("Running in region: {:?}", cx.region_id());
/// }
/// ```
#[inline]
#[must_use]
pub fn region_id(&self) -> RegionId {
self.inner.read().region
}
/// Returns the current task ID.
///
/// The task ID uniquely identifies this task within the runtime. Useful for
/// debugging, tracing, and correlating log entries.
///
/// # Example
///
/// ```ignore
/// fn log_task(cx: &Cx) {
/// println!("Task {:?} starting work", cx.task_id());
/// }
/// ```
#[inline]
#[must_use]
pub fn task_id(&self) -> TaskId {
self.inner.read().task
}
/// Returns the task type label, if one has been set.
///
/// Task types are optional metadata used by adaptive deadline monitoring
/// and metrics to group similar work.
#[inline]
#[must_use]
pub fn task_type(&self) -> Option<String> {
self.inner.read().task_type.clone()
}
/// Sets a task type label for adaptive monitoring and metrics.
///
/// This is intended to be called early in task execution to associate
/// a stable label with the task's behavior profile.
///
/// # Policy (br-asupersync-9vpwpc)
///
/// `task_type` is exported VERBATIM as an OpenTelemetry label by the
/// observability layer (see `src/observability/otel.rs`). To prevent
/// cardinality explosion against the metrics backend AND PII leakage
/// into telemetry pipelines, the value MUST be a fixed, low-cardinality
/// identifier:
///
/// * Length ≤ 64 bytes
/// * Charset: ASCII alphanumeric, `_`, `.`, `-`, `:` only (no
/// whitespace, no high-entropy characters typical of PII like
/// email addresses, UUIDs, or user IDs).
/// * First character: ASCII letter (matches OpenTelemetry naming
/// conventions and rejects formats like `"-leading-dash"`).
///
/// Values that violate the policy are SILENTLY DROPPED with a
/// `tracing::warn!` log instead of being stored — `set_task_type`'s
/// public signature returns `()` so we cannot surface the rejection
/// as `Err`. The warn includes a length-truncated preview so the
/// developer can find their offending call site without the full
/// PII content showing up in production logs again.
pub fn set_task_type(&self, task_type: impl Into<String>) {
let task_type = task_type.into();
if !is_valid_task_type(&task_type) {
// Truncate the offending value to 16 chars before logging so
// we don't replay PII into the same log pipeline we're
// trying to protect. This is enough for the developer to
// recognise the misuse without echoing user_ids verbatim.
let _preview: String = task_type.chars().take(16).collect();
warn!(
rejected_len = task_type.len(),
rejected_preview = %_preview,
"set_task_type: rejected high-cardinality / PII-shaped value \
(br-9vpwpc; must match [A-Za-z][A-Za-z0-9_.:-]{{0,63}})"
);
return;
}
let mut inner = self.inner.write();
inner.task_type = Some(task_type);
}
/// Returns the current budget.
///
/// The budget defines resource limits for this task:
/// - `deadline`: Absolute time limit
/// - `poll_quota`: Maximum number of polls
/// - `cost_quota`: Abstract cost units
/// - `priority`: Scheduling priority
///
/// Frameworks can use the budget to implement request timeouts:
///
/// # Example
///
/// ```ignore
/// async fn check_timeout(cx: &Cx) -> Result<(), TimeoutError> {
/// let budget = cx.budget();
/// if budget.is_expired() {
/// return Err(TimeoutError::DeadlineExceeded);
/// }
/// Ok(())
/// }
/// ```
#[inline]
#[must_use]
pub fn budget(&self) -> Budget {
self.inner.read().budget
}
/// Returns the explicit capability/resource budget carried by this context.
#[inline]
#[must_use]
pub fn capability_budget(&self) -> CapabilityBudget {
self.inner.read().capability_budget
}
/// Computes the effective child capability budget without mutating this
/// context.
///
/// Required dimensions fail closed if no parent or child budget supplies
/// them, or if the effective envelope is already exhausted.
#[inline]
pub fn plan_child_capability_budget(
&self,
child: CapabilityBudget,
requirements: CapabilityBudgetRequirements,
) -> Result<CapabilityBudget, CapabilityBudgetRefusal> {
self.inner
.read()
.capability_budget
.plan_child(child, requirements)
}
/// Applies a child capability budget to this context after fail-closed
/// validation.
///
/// This mutates the shared `CxInner`, so all clones observe the same
/// effective envelope. Use [`Self::plan_child_capability_budget`] when a
/// caller only needs an admission decision.
#[inline]
pub fn apply_child_capability_budget(
&self,
child: CapabilityBudget,
requirements: CapabilityBudgetRequirements,
) -> Result<CapabilityBudget, CapabilityBudgetRefusal> {
let mut inner = self.inner.write();
let effective = inner.capability_budget.plan_child(child, requirements)?;
inner.capability_budget = effective;
Ok(effective)
}
/// Returns true if cancellation has been requested.
///
/// This is a non-blocking check that queries whether a cancellation signal
/// has been sent to this task. Unlike `checkpoint()`, this method does not
/// return an error - it just reports the current state.
///
/// Frameworks should check this periodically during long-running operations
/// to enable graceful shutdown.
///
/// # Example
///
/// ```ignore
/// async fn process_items(cx: &Cx, items: Vec<Item>) -> Result<(), Error> {
/// for item in items {
/// // Check for cancellation between items
/// if cx.is_cancel_requested() {
/// return Err(Error::Cancelled);
/// }
/// process(item).await?;
/// }
/// Ok(())
/// }
/// ```
#[inline]
#[must_use]
pub fn is_cancel_requested(&self) -> bool {
self.inner.read().cancel_requested
}
/// Checks for cancellation and returns an error if cancelled.
///
/// This is a checkpoint where cancellation can be observed. It combines
/// checking the cancellation flag with returning an error, making it
/// convenient for use with the `?` operator.
///
/// In addition to cancellation checking, this method records progress by
/// updating the checkpoint state. This is useful for:
/// - Detecting stuck/stalled tasks via `checkpoint_state()`
/// - Work-stealing scheduler decisions
/// - Observability and debugging
///
/// If the context is currently masked (via `masked()`), this method
/// returns `Ok(())` even when cancellation is pending, deferring the
/// cancellation until the mask is released.
///
/// # Errors
///
/// Returns an `Err` with kind `ErrorKind::Cancelled` if cancellation is
/// pending and the context is not masked.
///
/// # Example
///
/// ```ignore
/// async fn do_work(cx: &Cx) -> Result<(), Error> {
/// // Use checkpoint with ? for concise cancellation handling
/// cx.checkpoint()?;
///
/// expensive_operation().await?;
///
/// cx.checkpoint()?;
///
/// another_operation().await?;
///
/// Ok(())
/// }
/// ```
/// Implements `rule.cancel.checkpoint_masked` (#10):
/// if cancel_requested and mask_depth == 0, acknowledge cancellation.
/// If mask_depth > 0, cancel remains deferred until mask is unwound.
#[allow(clippy::result_large_err)]
pub fn checkpoint(&self) -> Result<(), crate::error::Error> {
let checkpoint_time = self.current_checkpoint_time();
// ── Fast path (br-asupersync-is2xg0) ──────────────────────────────
// The vast majority of checkpoint() calls fire on healthy tasks
// with no cancellation pending and no budget exhaustion. Take a
// read lock, atomically check `fast_cancel`, snapshot the (Copy)
// budget to detect deadline / poll / cost exhaustion inline, and
// record progress via two atomic ops — without acquiring the
// write lock or cloning `cancel_reason`.
//
// Correctness: `fast_cancel` is set with `Release` ordering by
// every cancellation source (TaskHandle::cancel, deadline_monitor,
// and the slow path below when it newly observes exhaustion). An
// `Acquire` load here therefore observes any prior cancellation.
// Budget exhaustion is checked inline so unit-test invariants
// ("checkpoint detects deadline / poll-quota / cost-budget
// exhaustion") are preserved without going through deadline_monitor.
{
let guard = self.inner.read();
let cancelled = guard.fast_cancel.load(std::sync::atomic::Ordering::Acquire);
let exhausted = !cancelled
&& Self::checkpoint_budget_exhaustion(
guard.region,
guard.task,
guard.budget,
checkpoint_time,
)
.is_some();
// Fast path must also check if there's a message to clear
let has_message = guard.checkpoint_state.last_message.is_some();
// First checkpoint must go through slow path for proper initialization
let is_first_checkpoint = guard.checkpoint_state.checkpoint_count == 0
&& guard
.fast_path_count
.load(std::sync::atomic::Ordering::Relaxed)
== 0;
if !cancelled && !exhausted && !has_message && !is_first_checkpoint {
guard.fast_path_last_checkpoint_ns.store(
checkpoint_time.as_nanos(),
std::sync::atomic::Ordering::Relaxed,
);
guard
.fast_path_count
.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
return Ok(());
}
}
// ── Slow path ─────────────────────────────────────────────────────
// Cancellation is pending. Acquire the write lock, drain any
// fast-path checkpoint accounting into the authoritative
// CheckpointState, then run the existing logic unchanged.
let (
cancel_requested,
mask_depth,
task,
region,
budget,
budget_baseline,
cancel_reason,
budget_exhaustion,
) = {
let mut inner = self.inner.write();
inner.drain_fast_path_checkpoint();
inner.checkpoint_state.record_at(checkpoint_time);
let budget_exhaustion = Self::checkpoint_budget_exhaustion(
inner.region,
inner.task,
inner.budget,
checkpoint_time,
);
if let Some((reason, _, _)) = &budget_exhaustion {
inner.cancel_requested = true;
inner
.fast_cancel
.store(true, std::sync::atomic::Ordering::Release);
if let Some(existing) = &mut inner.cancel_reason {
existing.strengthen(reason);
} else {
inner.cancel_reason = Some(reason.clone());
}
}
if inner.cancel_requested && inner.mask_depth == 0 {
inner.cancel_acknowledged = true;
}
(
inner.cancel_requested,
inner.mask_depth,
inner.task,
inner.region,
inner.budget,
inner.budget_baseline,
inner.cancel_reason.clone(),
budget_exhaustion.map(|(_, exhaustion_kind, deadline_remaining_ms)| {
(exhaustion_kind, deadline_remaining_ms)
}),
)
};
if let Some((exhaustion_kind, deadline_remaining_ms)) = budget_exhaustion {
if let Some(ref sink) = self.handles.evidence_sink {
crate::evidence_sink::emit_budget_evidence(
sink.as_ref(),
exhaustion_kind,
budget.poll_quota,
deadline_remaining_ms,
);
}
}
// Emit evidence for cancellation decisions observed at checkpoint.
if cancel_requested && mask_depth == 0 {
if let Some(ref sink) = self.handles.evidence_sink {
let kind_str = cancel_reason
.as_ref()
.map_or_else(|| "unknown".to_string(), |r| format!("{}", r.kind));
crate::evidence_sink::emit_cancel_evidence(
sink.as_ref(),
&kind_str,
budget.poll_quota,
budget.priority,
);
}
}
Self::check_cancel_from_values(
cancel_requested,
mask_depth,
task,
region,
budget,
budget_baseline,
checkpoint_time,
cancel_reason.as_ref(),
)
}
/// Checks for cancellation with a progress message.
///
/// This is like [`checkpoint()`](Self::checkpoint) but also records a
/// human-readable message describing the current progress. The message
/// is stored in the checkpoint state and can be retrieved via
/// [`checkpoint_state()`](Self::checkpoint_state).
///
/// # Errors
///
/// Returns an `Err` with kind `ErrorKind::Cancelled` if cancellation is
/// pending and the context is not masked.
///
/// # Example
///
/// ```ignore
/// async fn process_batch(cx: &Cx, items: &[Item]) -> Result<(), Error> {
/// for (i, item) in items.iter().enumerate() {
/// cx.checkpoint_with(format!("Processing item {}/{}", i + 1, items.len()))?;
/// process(item).await?;
/// }
/// Ok(())
/// }
/// ```
#[allow(clippy::result_large_err)]
pub fn checkpoint_with(&self, msg: impl Into<String>) -> Result<(), crate::error::Error> {
let checkpoint_time = self.current_checkpoint_time();
// checkpoint_with always takes the write lock because the message
// must be stored in CheckpointState under the lock, but we still
// drain any pending fast-path accounting first so checkpoint_count
// and last_checkpoint stay monotonic relative to fast checkpoints.
// (br-asupersync-is2xg0)
let (
cancel_requested,
mask_depth,
task,
region,
budget,
budget_baseline,
cancel_reason,
budget_exhaustion,
) = {
let mut inner = self.inner.write();
inner.drain_fast_path_checkpoint();
inner
.checkpoint_state
.record_with_message_at(msg.into(), checkpoint_time);
let budget_exhaustion = Self::checkpoint_budget_exhaustion(
inner.region,
inner.task,
inner.budget,
checkpoint_time,
);
if let Some((reason, _, _)) = &budget_exhaustion {
inner.cancel_requested = true;
inner
.fast_cancel
.store(true, std::sync::atomic::Ordering::Release);
if let Some(existing) = &mut inner.cancel_reason {
existing.strengthen(reason);
} else {
inner.cancel_reason = Some(reason.clone());
}
}
if inner.cancel_requested && inner.mask_depth == 0 {
inner.cancel_acknowledged = true;
}
(
inner.cancel_requested,
inner.mask_depth,
inner.task,
inner.region,
inner.budget,
inner.budget_baseline,
inner.cancel_reason.clone(),
budget_exhaustion.map(|(_, exhaustion_kind, deadline_remaining_ms)| {
(exhaustion_kind, deadline_remaining_ms)
}),
)
};
if let Some((exhaustion_kind, deadline_remaining_ms)) = budget_exhaustion {
if let Some(ref sink) = self.handles.evidence_sink {
crate::evidence_sink::emit_budget_evidence(
sink.as_ref(),
exhaustion_kind,
budget.poll_quota,
deadline_remaining_ms,
);
}
}
// Emit evidence for cancellation decisions observed at checkpoint.
if cancel_requested && mask_depth == 0 {
if let Some(ref sink) = self.handles.evidence_sink {
let kind_str = cancel_reason
.as_ref()
.map_or_else(|| "unknown".to_string(), |r| format!("{}", r.kind));
crate::evidence_sink::emit_cancel_evidence(
sink.as_ref(),
&kind_str,
budget.poll_quota,
budget.priority,
);
}
}
Self::check_cancel_from_values(
cancel_requested,
mask_depth,
task,
region,
budget,
budget_baseline,
checkpoint_time,
cancel_reason.as_ref(),
)
}
/// Returns a snapshot of the current checkpoint state.
///
/// The checkpoint state tracks progress reporting checkpoints:
/// - `last_checkpoint`: The runtime time when the last checkpoint was recorded
/// - `last_message`: The message from the last `checkpoint_with()` call
/// - `checkpoint_count`: Total number of checkpoints
///
/// This is useful for monitoring task progress and detecting stalled tasks.
///
/// # Example
///
/// ```ignore
/// fn check_task_health(cx: &Cx) -> bool {
/// let state = cx.checkpoint_state();
/// state.last_checkpoint.is_some()
/// }
/// ```
#[must_use]
pub fn checkpoint_state(&self) -> crate::types::CheckpointState {
// Materialise: clone the authoritative state PLUS merge any pending
// fast-path checkpoint accounting that hasn't been drained yet
// (br-asupersync-is2xg0).
self.inner.read().materialised_checkpoint_state()
}
/// Returns the current physical time according to the configured timer driver,
/// or the wall clock if no timer driver is available.
#[must_use]
pub fn now(&self) -> Time
where
Caps: cap::HasTime,
{
self.handles
.timer_driver
.as_ref()
.map_or_else(wall_clock_now, TimerDriverHandle::now)
}
/// Internal: returns current time for checkpointing.
#[inline]
fn current_checkpoint_time(&self) -> Time {
self.handles
.timer_driver
.as_ref()
.map_or_else(wall_clock_now, TimerDriverHandle::now)
}
/// Returns the current time from the configured timer driver, falling back
/// to wall-clock when no driver is installed.
///
/// Unlike [`now`], this method does not require the `HasTime` capability.
/// It is intended for observability/diagnostic code that wants replayable
/// timestamps in lab mode without threading a `HasTime`-capable `Cx`
/// through. Production behavior is identical to `now`.
#[must_use]
#[inline]
pub fn now_for_observability(&self) -> Time {
self.current_checkpoint_time()
}
#[inline]
fn checkpoint_budget_exhaustion(
region: RegionId,
task: TaskId,
budget: Budget,
now: Time,
) -> Option<(CancelReason, &'static str, Option<u64>)> {
let deadline_remaining_ms = budget
.remaining_time(now)
.map(Self::duration_millis_saturating);
let mut exhaustion = if budget.is_past_deadline(now) {
Some((
CancelReason::with_origin(CancelKind::Deadline, region, now).with_task(task),
"time",
deadline_remaining_ms,
))
} else {
None
};
if budget.poll_quota == 0 {
let candidate =
CancelReason::with_origin(CancelKind::PollQuota, region, now).with_task(task);
match &mut exhaustion {
Some((existing, kind, _)) => {
if existing.strengthen(&candidate) {
*kind = "poll";
}
}
None => exhaustion = Some((candidate, "poll", deadline_remaining_ms)),
}
}
if matches!(budget.cost_quota, Some(0)) {
let candidate =
CancelReason::with_origin(CancelKind::CostBudget, region, now).with_task(task);
match &mut exhaustion {
Some((existing, kind, _)) => {
if existing.strengthen(&candidate) {
*kind = "cost";
}
}
None => exhaustion = Some((candidate, "cost", deadline_remaining_ms)),
}
}
exhaustion
}
#[inline]
fn checkpoint_budget_usage(
budget: Budget,
budget_baseline: Budget,
now: Time,
) -> (Option<u32>, Option<u64>, Option<u64>) {
let polls_used = if budget_baseline.poll_quota == u32::MAX {
None
} else {
Some(budget_baseline.poll_quota.saturating_sub(budget.poll_quota))
};
let cost_used = match (budget_baseline.cost_quota, budget.cost_quota) {
(Some(baseline), Some(remaining)) => Some(baseline.saturating_sub(remaining)),
_ => None,
};
let time_remaining_ms = budget
.remaining_time(now)
.map(Self::duration_millis_saturating);
(polls_used, cost_used, time_remaining_ms)
}
#[inline]
fn duration_millis_saturating(duration: Duration) -> u64 {
u64::try_from(duration.as_millis()).unwrap_or(u64::MAX)
}
/// Internal: checks cancellation from extracted values.
#[allow(clippy::result_large_err)]
#[allow(clippy::too_many_arguments)]
fn check_cancel_from_values(
cancel_requested: bool,
mask_depth: u32,
task: TaskId,
region: RegionId,
budget: Budget,
budget_baseline: Budget,
checkpoint_time: Time,
cancel_reason: Option<&CancelReason>,
) -> Result<(), crate::error::Error> {
let (polls_used, cost_used, time_remaining_ms) =
Self::checkpoint_budget_usage(budget, budget_baseline, checkpoint_time);
let _ = (
&task,
®ion,
&budget,
&budget_baseline,
&polls_used,
&cost_used,
&time_remaining_ms,
);
trace!(
task_id = ?task,
region_id = ?region,
polls_used = ?polls_used,
polls_remaining = budget.poll_quota,
time_remaining_ms = ?time_remaining_ms,
cost_used = ?cost_used,
cost_remaining = ?budget.cost_quota,
deadline = ?budget.deadline,
cancel_reason = ?cancel_reason,
cancel_requested,
mask_depth,
"checkpoint"
);
if cancel_requested {
if mask_depth == 0 {
let cancel_reason_ref = cancel_reason.as_ref();
let exhausted_resource = cancel_reason_ref
.map_or_else(|| "unknown".to_string(), |r| format!("{:?}", r.kind));
let _ = &exhausted_resource;
info!(
task_id = ?task,
region_id = ?region,
exhausted_resource = %exhausted_resource,
cancel_reason = ?cancel_reason,
budget_deadline = ?budget.deadline,
budget_poll_quota = budget.poll_quota,
budget_cost_quota = ?budget.cost_quota,
"cancel observed at checkpoint - task cancelled"
);
trace!(
task_id = ?task,
region_id = ?region,
cancel_reason = ?cancel_reason,
cancel_kind = ?cancel_reason.as_ref().map(|r| r.kind),
mask_depth,
budget_deadline = ?budget.deadline,
budget_poll_quota = budget.poll_quota,
budget_cost_quota = ?budget.cost_quota,
budget_priority = budget.priority,
"cancel observed at checkpoint"
);
Err(crate::error::Error::new(crate::error::ErrorKind::Cancelled))
} else {
trace!(
task_id = ?task,
region_id = ?region,
cancel_reason = ?cancel_reason,
cancel_kind = ?cancel_reason.as_ref().map(|r| r.kind),
mask_depth,
"cancel observed but masked"
);
Ok(())
}
} else {
Ok(())
}
}
/// Executes a closure with cancellation masked.
///
/// While masked, `checkpoint()` will return `Ok(())` even if cancellation
/// has been requested. This is used for critical sections that must not
/// be interrupted, such as:
///
/// - Completing a two-phase commit
/// - Flushing buffered data
/// - Releasing resources in a specific order
///
/// Masking can be nested - each call to `masked()` increments a depth
/// counter, and cancellation is only observable when depth returns to 0.
///
/// # Example
///
/// ```ignore
/// async fn commit_transaction(cx: &Cx, tx: Transaction) -> Result<(), Error> {
/// // Critical section: must complete even if cancelled
/// cx.masked(|| {
/// tx.prepare()?;
/// tx.commit()?; // Cannot be interrupted here
/// Ok(())
/// })
/// }
/// ```
///
/// # Note
///
/// Use masking sparingly. Long-masked sections defeat the purpose of
/// responsive cancellation. Prefer short critical sections followed
/// by a checkpoint.
///
/// Invariant `inv.cancel.mask_monotone` (#12): mask_depth is monotonically
/// non-increasing during cancel processing. The increment here occurs before
/// cancel acknowledgement; `MaskGuard::drop` decrements via `saturating_sub(1)`.
/// Invariant `inv.cancel.mask_bounded` (#11): mask_depth <= MAX_MASK_DEPTH.
pub fn masked<F, R>(&self, f: F) -> R
where
F: FnOnce() -> R,
{
{
let mut inner = self.inner.write();
// Enforce mask depth cap to prevent overflow and infinite recursion
// This maintains INV-MASK-BOUNDED invariant in both debug and release builds
assert!(
inner.mask_depth < crate::types::task_context::MAX_MASK_DEPTH,
"mask depth exceeded MAX_MASK_DEPTH ({}): this violates INV-MASK-BOUNDED \
and prevents cancellation from ever being observed. \
Reduce nesting of Cx::masked() sections.",
crate::types::task_context::MAX_MASK_DEPTH,
);
inner.mask_depth += 1;
}
let _guard = MaskGuard { inner: &self.inner };
f()
}
/// Traces an event for observability.
///
/// Trace events are associated with the current task and region, enabling
/// structured observability. In the lab runtime, traces are captured
/// deterministically for replay and debugging.
///
/// # Example
///
/// ```ignore
/// async fn process_request(cx: &Cx, request: &Request) -> Response {
/// cx.trace("Request received");
///
/// let result = handle(request).await;
///
/// cx.trace("Request processed");
///
/// result
/// }
/// ```
///
/// # Note
///
/// When a trace buffer is attached to this `Cx`, this writes a structured
/// user trace event into that buffer and also emits to the log collector.
/// Without a trace buffer, it still records the log entry.
pub fn trace(&self, message: &str) {
self.log(LogEntry::trace(message));
let Some(trace) = self.trace_buffer() else {
return;
};
let now = self
.handles
.timer_driver
.as_ref()
.map_or_else(wall_clock_now, TimerDriverHandle::now);
let logical_time = self.logical_tick();
trace.record_event(move |seq| {
TraceEvent::user_trace(seq, now, message).with_logical_time(logical_time)
});
}
/// Logs a trace-level message with structured key-value fields.
///
/// Each field is attached to the resulting `LogEntry`, making it
/// queryable in the log collector.
///
/// # Example
///
/// ```ignore
/// cx.trace_with_fields("request handled", &[
/// ("method", "GET"),
/// ("path", "/api/users"),
/// ("status", "200"),
/// ]);
/// ```
pub fn trace_with_fields(&self, message: &str, fields: &[(&str, &str)]) {
let mut entry = LogEntry::trace(message);
for &(k, v) in fields {
entry = entry.with_field(k, v);
}
self.log(entry);
let Some(trace) = self.trace_buffer() else {
return;
};
let now = self
.handles
.timer_driver
.as_ref()
.map_or_else(wall_clock_now, TimerDriverHandle::now);
let logical_time = self.logical_tick();
trace.record_event(move |seq| {
TraceEvent::user_trace(seq, now, message).with_logical_time(logical_time)
});
}
/// Enters a named span, returning a guard that ends the span on drop.
///
/// The span forks the current `DiagnosticContext`, assigning a new
/// `SpanId` with the previous span as parent. When the guard is
/// dropped the original context is restored.
///
/// # Example
///
/// ```ignore
/// {
/// let _guard = cx.enter_span("parse_request");
/// // ... work inside the span ...
/// } // span ends here
/// ```
#[must_use]
pub fn enter_span(&self, name: &str) -> SpanGuard<Caps> {
let prev = self.diagnostic_context();
let child = prev.fork().with_custom("span.name", name);
self.set_diagnostic_context(child);
self.log(LogEntry::debug(format!("span enter: {name}")).with_target("tracing"));
SpanGuard {
cx: self.clone(),
prev,
}
}
/// Sets a request correlation ID on the diagnostic context.
///
/// The ID propagates to all log entries and child spans created
/// from this context, enabling end-to-end request tracing.
pub fn set_request_id(&self, id: impl Into<String>) {
let mut obs = self.observability.write();
obs.context = obs.context.clone().with_custom("request_id", id);
}
/// Returns the current request correlation ID, if set.
#[inline]
#[must_use]
pub fn request_id(&self) -> Option<String> {
self.diagnostic_context()
.custom("request_id")
.map(String::from)
}
/// Logs a structured entry to the attached collector, if present.
pub fn log(&self, entry: LogEntry) {
let obs = self.observability.read();
let Some(collector) = obs.collector.clone() else {
return;
};
let include_timestamps = obs.include_timestamps;
let context = obs.context.clone();
drop(obs);
let mut entry = entry.with_context(&context);
if include_timestamps && entry.timestamp() == Time::from_nanos(1_000_000_000) {
let now = self
.handles
.timer_driver
.as_ref()
.map_or_else(wall_clock_now, TimerDriverHandle::now);
entry = entry.with_timestamp(now);
}
collector.log(entry);
}
/// Returns a snapshot of the current diagnostic context.
#[must_use]
pub fn diagnostic_context(&self) -> DiagnosticContext {
self.observability.read().context.clone()
}
/// Replaces the current diagnostic context.
pub fn set_diagnostic_context(&self, ctx: DiagnosticContext) {
let mut obs = self.observability.write();
obs.context = ctx;
}
/// Attaches a log collector to this context.
pub fn set_log_collector(&self, collector: LogCollector) {
let mut obs = self.observability.write();
obs.collector = Some(collector);
}
/// Returns the current log collector, if attached.
#[inline]
#[must_use]
pub fn log_collector(&self) -> Option<LogCollector> {
self.observability.read().collector.clone()
}
/// Attaches a trace buffer to this context.
pub fn set_trace_buffer(&self, trace: TraceBufferHandle) {
let mut obs = self.observability.write();
obs.trace = Some(trace);
}
/// Attaches the shared loser-drain history recorder to this context.
pub(crate) fn set_loser_drain_history_handle(&self, history: LoserDrainHistoryHandle) {
let mut obs = self.observability.write();
obs.loser_drain_history = Some(history);
}
/// Returns the current trace buffer handle, if attached.
#[inline]
#[must_use]
pub fn trace_buffer(&self) -> Option<TraceBufferHandle> {
self.observability.read().trace.clone()
}
#[inline]
#[must_use]
#[allow(dead_code)]
pub(crate) fn loser_drain_history_handle(&self) -> Option<LoserDrainHistoryHandle> {
self.observability.read().loser_drain_history.clone()
}
/// Derives an observability state for a child task.
pub(crate) fn child_observability(&self, region: RegionId, task: TaskId) -> ObservabilityState {
let obs = self.observability.read();
obs.derive_child(region, task)
}
/// Returns the entropy source for this context.
#[inline]
#[must_use]
pub fn entropy(&self) -> &dyn EntropySource
where
Caps: cap::HasRandom,
{
self.handles.entropy.as_ref()
}
/// Derives an entropy source for a child task.
pub(crate) fn child_entropy(&self, task: TaskId) -> Arc<dyn EntropySource> {
self.handles.entropy.fork(task)
}
/// Returns a cloned entropy handle for capability-aware subsystems.
#[inline]
#[must_use]
pub(crate) fn entropy_handle(&self) -> Arc<dyn EntropySource>
where
Caps: cap::HasRandom,
{
self.handles.entropy.clone()
}
/// Generates a random `u64` using the context entropy source.
#[must_use]
pub fn random_u64(&self) -> u64
where
Caps: cap::HasRandom,
{
let value = self.handles.entropy.next_u64();
// br-asupersync-lw9q66: do NOT log the random value. If
// random_u64 is used to generate cryptographic material
// (keys, nonces, IVs, seeds, salts), including the value in
// a trace event leaks the secret to anything reading the
// trace stream — log files, distributed trace exports,
// ring-buffer dumps, etc. Trace fields stay limited to
// diagnostic non-sensitive data (source + task_id), matching
// the random_bytes log shape (which only records `len`).
trace!(
source = self.handles.entropy.source_id(),
task_id = ?self.task_id(),
"entropy_u64"
);
value
}
/// Fills a buffer with random bytes using the context entropy source.
pub fn random_bytes(&self, dest: &mut [u8])
where
Caps: cap::HasRandom,
{
self.handles.entropy.fill_bytes(dest);
trace!(
source = self.handles.entropy.source_id(),
task_id = ?self.task_id(),
len = dest.len(),
"entropy_bytes"
);
}
/// Generates a random `usize` in `[0, bound)` with rejection sampling.
#[must_use]
pub fn random_usize(&self, bound: usize) -> usize
where
Caps: cap::HasRandom,
{
assert!(bound > 0, "bound must be non-zero");
let bound_u64 = bound as u64;
let threshold = u64::MAX - (u64::MAX % bound_u64);
loop {
let value = self.random_u64();
if value < threshold {
return (value % bound_u64) as usize;
}
}
}
/// Generates a random boolean.
#[must_use]
pub fn random_bool(&self) -> bool
where
Caps: cap::HasRandom,
{
self.random_u64() & 1 == 1
}
/// Generates a random `f64` in `[0, 1)`.
#[must_use]
#[allow(clippy::cast_precision_loss)]
pub fn random_f64(&self) -> f64
where
Caps: cap::HasRandom,
{
(self.random_u64() >> 11) as f64 / (1u64 << 53) as f64
}
/// Shuffles a slice in place using Fisher-Yates.
pub fn shuffle<T>(&self, slice: &mut [T])
where
Caps: cap::HasRandom,
{
for i in (1..slice.len()).rev() {
let j = self.random_usize(i + 1);
slice.swap(i, j);
}
}
/// Sets the cancellation flag (internal use).
#[allow(dead_code)]
pub(crate) fn set_cancel_internal(&self, value: bool) {
let mut inner = self.inner.write();
inner.cancel_requested = value;
inner
.fast_cancel
.store(value, std::sync::atomic::Ordering::Release);
if !value {
inner.cancel_reason = None;
}
}
/// Sets the cancellation flag for testing purposes.
///
/// This method allows tests to simulate cancellation signals. It sets the
/// `cancel_requested` flag, which will cause subsequent `checkpoint()` calls
/// to return an error (unless masked).
///
/// # Example
///
/// ```
/// use asupersync::Cx;
///
/// let cx = Cx::for_testing();
/// assert!(cx.checkpoint().is_ok());
///
/// cx.set_cancel_requested(true);
/// assert!(cx.checkpoint().is_err());
/// ```
///
/// # Note
///
/// This API is intended for testing only. In production, cancellation signals
/// are propagated by the runtime through the task tree.
pub fn set_cancel_requested(&self, value: bool) {
let waker = {
let mut inner = self.inner.write();
inner.cancel_requested = value;
inner
.fast_cancel
.store(value, std::sync::atomic::Ordering::Release);
if !value {
inner.cancel_reason = None;
None
} else {
inner.cancel_waker.clone()
}
};
if let Some(waker) = waker {
waker.wake();
}
}
// ========================================================================
// Cancel Attribution API
// ========================================================================
/// Cancels this context with a detailed reason.
///
/// This is the preferred method for initiating cancellation, as it provides
/// complete attribution information. The reason includes:
/// - The kind of cancellation (e.g., User, Timeout, Deadline)
/// - An optional message explaining the cancellation
/// - Origin region and task information (automatically set)
///
/// # Arguments
///
/// * `kind` - The type of cancellation being initiated
/// * `message` - An optional human-readable message explaining why
///
/// # Example
///
/// ```
/// use asupersync::{Cx, types::CancelKind};
///
/// let cx = Cx::for_testing();
/// cx.cancel_with(CancelKind::User, Some("User pressed Ctrl+C"));
/// assert!(cx.is_cancel_requested());
///
/// if let Some(reason) = cx.cancel_reason() {
/// assert_eq!(reason.kind, CancelKind::User);
/// }
/// ```
///
/// # Note
///
/// This method only sets the local cancellation flag. In a real runtime,
/// cancellation propagates through the region tree via `cancel_request()`.
pub fn cancel_with(&self, kind: CancelKind, message: Option<&'static str>) {
let (region, task, waker) = {
let mut inner = self.inner.write();
let region = inner.region;
let task = inner.task;
let mut reason = CancelReason::new(kind).with_region(region).with_task(task);
if let Some(msg) = message {
reason = reason.with_message(msg);
}
inner.cancel_requested = true;
inner
.fast_cancel
.store(true, std::sync::atomic::Ordering::Release);
inner.cancel_reason = Some(reason);
let waker = inner.cancel_waker.clone();
drop(inner);
(region, task, waker)
};
if let Some(w) = waker {
w.wake();
}
debug!(
task_id = ?task,
region_id = ?region,
cancel_kind = ?kind,
cancel_message = message,
"cancel initiated via cancel_with"
);
let _ = (region, task);
}
/// Cancels without building a full attribution chain (performance-critical path).
///
/// Use this when attribution isn't needed and minimizing allocations is important.
/// The cancellation reason will have minimal attribution (kind + region only).
///
/// # Performance
///
/// This method avoids:
/// - Message string allocation
/// - Cause chain allocation
/// - Timestamp lookup
///
/// Use `cancel_with` when you need full attribution for debugging.
///
/// # Example
///
/// ```
/// use asupersync::{Cx, types::CancelKind};
///
/// let cx = Cx::for_testing();
///
/// // Fast cancellation - no allocation
/// cx.cancel_fast(CancelKind::RaceLost);
/// assert!(cx.is_cancel_requested());
/// ```
pub fn cancel_fast(&self, kind: CancelKind) {
let (region, waker) = {
let mut inner = self.inner.write();
let region = inner.region;
// Minimal attribution: just kind and region
let reason = CancelReason::new(kind).with_region(region);
inner.cancel_requested = true;
inner
.fast_cancel
.store(true, std::sync::atomic::Ordering::Release);
inner.cancel_reason = Some(reason);
let waker = inner.cancel_waker.clone();
drop(inner);
(region, waker)
};
if let Some(w) = waker {
w.wake();
}
trace!(
region_id = ?region,
cancel_kind = ?kind,
"cancel_fast initiated"
);
let _ = region;
}
/// Gets the cancellation reason if this context is cancelled.
///
/// Returns `None` if the context is not cancelled, or `Some(reason)` if
/// cancellation has been requested. The returned reason includes full
/// attribution (kind, origin region, origin task, timestamp, cause chain).
///
/// # Example
///
/// ```
/// use asupersync::{Cx, types::CancelKind};
///
/// let cx = Cx::for_testing();
/// assert!(cx.cancel_reason().is_none());
///
/// cx.cancel_with(CancelKind::Timeout, Some("request timeout"));
/// if let Some(reason) = cx.cancel_reason() {
/// assert_eq!(reason.kind, CancelKind::Timeout);
/// println!("Cancelled: {:?}", reason.kind);
/// }
/// ```
#[inline]
#[must_use]
pub fn cancel_reason(&self) -> Option<CancelReason> {
let inner = self.inner.read();
inner.cancel_reason.clone()
}
/// Iterates through the full cancellation cause chain.
///
/// The first element is the immediate reason, followed by parent causes
/// in order (immediate -> root). This is useful for understanding the
/// full propagation path of a cancellation.
///
/// Returns an empty iterator if the context is not cancelled.
///
/// # Example
///
/// ```
/// use asupersync::{Cx, types::{CancelKind, CancelReason}};
///
/// let cx = Cx::for_testing();
///
/// // Create a chained reason: ParentCancelled -> Deadline
/// let root_cause = CancelReason::deadline();
/// let chained = CancelReason::parent_cancelled().with_cause(root_cause);
///
/// // Set it via internal method for testing
/// cx.set_cancel_reason(chained);
///
/// let chain: Vec<_> = cx.cancel_chain().collect();
/// assert_eq!(chain.len(), 2);
/// assert_eq!(chain[0].kind, CancelKind::ParentCancelled);
/// assert_eq!(chain[1].kind, CancelKind::Deadline);
/// ```
pub fn cancel_chain(&self) -> impl Iterator<Item = CancelReason> {
let cancel_reason = self.inner.read().cancel_reason.clone();
std::iter::successors(cancel_reason, |r| r.cause.as_deref().cloned())
}
/// Gets the root cause of cancellation.
///
/// This is the original trigger that initiated the cancellation, regardless
/// of how many parent regions the cancellation propagated through. For example,
/// if a grandchild task was cancelled due to a parent timeout, `root_cancel_cause()`
/// returns the original Timeout reason, not the intermediate ParentCancelled reasons.
///
/// Returns `None` if the context is not cancelled.
///
/// # Example
///
/// ```
/// use asupersync::{Cx, types::{CancelKind, CancelReason}};
///
/// let cx = Cx::for_testing();
///
/// // Simulate a deep cancellation chain
/// let deadline = CancelReason::deadline();
/// let parent1 = CancelReason::parent_cancelled().with_cause(deadline);
/// let parent2 = CancelReason::parent_cancelled().with_cause(parent1);
///
/// cx.set_cancel_reason(parent2);
///
/// // Root cause is the original Deadline, not ParentCancelled
/// if let Some(root) = cx.root_cancel_cause() {
/// assert_eq!(root.kind, CancelKind::Deadline);
/// }
/// ```
#[must_use]
pub fn root_cancel_cause(&self) -> Option<CancelReason> {
let inner = self.inner.read();
inner.cancel_reason.as_ref().map(|r| r.root_cause().clone())
}
/// Checks if cancellation was due to a specific kind.
///
/// This checks the immediate reason only, not the cause chain. For example,
/// if a task was cancelled with `ParentCancelled` due to an upstream timeout,
/// `cancelled_by(CancelKind::ParentCancelled)` returns `true` but
/// `cancelled_by(CancelKind::Timeout)` returns `false`.
///
/// Use `any_cause_is()` to check the full cause chain.
///
/// # Example
///
/// ```
/// use asupersync::{Cx, types::CancelKind};
///
/// let cx = Cx::for_testing();
/// cx.cancel_with(CancelKind::User, Some("manual cancel"));
///
/// assert!(cx.cancelled_by(CancelKind::User));
/// assert!(!cx.cancelled_by(CancelKind::Timeout));
/// ```
#[must_use]
pub fn cancelled_by(&self, kind: CancelKind) -> bool {
let inner = self.inner.read();
inner.cancel_reason.as_ref().is_some_and(|r| r.kind == kind)
}
/// Checks if any cause in the chain is a specific kind.
///
/// This searches the entire cause chain, from the immediate reason to the
/// root cause. This is useful for checking if a specific condition (like
/// a timeout) anywhere in the hierarchy caused this cancellation.
///
/// # Example
///
/// ```
/// use asupersync::{Cx, types::{CancelKind, CancelReason}};
///
/// let cx = Cx::for_testing();
///
/// // Grandchild cancelled due to parent timeout
/// let timeout = CancelReason::timeout();
/// let parent_cancelled = CancelReason::parent_cancelled().with_cause(timeout);
///
/// cx.set_cancel_reason(parent_cancelled);
///
/// // Immediate reason is ParentCancelled, but timeout is in the chain
/// assert!(cx.cancelled_by(CancelKind::ParentCancelled));
/// assert!(!cx.cancelled_by(CancelKind::Timeout)); // immediate only
/// assert!(cx.any_cause_is(CancelKind::Timeout)); // searches chain
/// assert!(cx.any_cause_is(CancelKind::ParentCancelled)); // also in chain
/// ```
#[must_use]
pub fn any_cause_is(&self, kind: CancelKind) -> bool {
let inner = self.inner.read();
inner
.cancel_reason
.as_ref()
.is_some_and(|r| r.any_cause_is(kind))
}
/// Sets the cancellation reason (for testing purposes).
///
/// This method allows tests to set a specific cancellation reason, including
/// complex cause chains. It sets both the `cancel_requested` flag and the
/// `cancel_reason`.
///
/// # Example
///
/// ```
/// use asupersync::{Cx, types::{CancelKind, CancelReason}};
///
/// let cx = Cx::for_testing();
///
/// // Create a chained reason for testing
/// let root = CancelReason::deadline();
/// let chained = CancelReason::parent_cancelled().with_cause(root);
///
/// cx.set_cancel_reason(chained);
///
/// assert!(cx.is_cancel_requested());
/// assert_eq!(cx.cancel_reason().unwrap().kind, CancelKind::ParentCancelled);
/// ```
pub fn set_cancel_reason(&self, reason: CancelReason) {
let waker = {
let mut inner = self.inner.write();
inner.cancel_requested = true;
inner
.fast_cancel
.store(true, std::sync::atomic::Ordering::Release);
inner.cancel_reason = Some(reason);
inner.cancel_waker.clone()
};
if let Some(w) = waker {
w.wake();
}
}
/// Races multiple futures, waiting for the first to complete.
///
/// This method is used by the `race!` macro. It runs the provided futures
/// concurrently (inline, not spawned) and returns the result of the first
/// one to complete. Losers are dropped (cancelled).
///
/// # Cancellation vs Draining
///
/// This method **drops** the losing futures, which cancels them. However,
/// unlike [`Scope::race`](crate::cx::Scope::race), it does not await the
/// losers to ensure they have fully cleaned up ("drained").
///
/// If you are racing [`TaskHandle`](crate::runtime::TaskHandle)s and require
/// the "Losers are drained" invariant (parent waits for losers to terminate),
/// use [`Scope::race`](crate::cx::Scope::race) or
/// [`Scope::race_all`](crate::cx::Scope::race_all) instead.
pub async fn race<T>(
&self,
futures: Vec<Pin<Box<dyn Future<Output = T> + Send>>>,
) -> Result<T, JoinError> {
if futures.is_empty() {
return std::future::poll_fn(|_poll_cx| {
if self.checkpoint().is_err() {
let reason = self
.cancel_reason()
.unwrap_or_else(|| CancelReason::user("race cancelled"));
std::task::Poll::Ready(Err(JoinError::Cancelled(reason)))
} else {
std::task::Poll::Pending
}
})
.await;
}
let (res, _) = SelectAll::new(futures)
.await
.map_err(|_| JoinError::PolledAfterCompletion)?;
Ok(res)
}
/// Races multiple named futures.
///
/// Similar to `race`, but accepts names for tracing purposes.
///
/// # Cancellation vs Draining
///
/// This method **drops** the losing futures, which cancels them. However,
/// unlike [`Scope::race`](crate::cx::Scope::race), it does not await the
/// losers to ensure they have fully cleaned up ("drained").
pub async fn race_named<T>(&self, futures: NamedFutures<T>) -> Result<T, JoinError> {
let futures: Vec<_> = futures.into_iter().map(|(_, f)| f).collect();
self.race(futures).await
}
/// Races multiple futures with a timeout.
///
/// If the timeout expires before any future completes, returns a cancellation error.
///
/// # Cancellation vs Draining
///
/// This method **drops** the losing futures (or all futures on timeout),
/// which cancels them. However, it does not await the losers to ensure
/// they have fully cleaned up ("drained").
pub async fn race_timeout<T>(
&self,
duration: Duration,
futures: Vec<Pin<Box<dyn Future<Output = T> + Send>>>,
) -> Result<T, JoinError>
where
Caps: cap::HasTime,
{
let race_fut = std::pin::pin!(self.race(futures));
let now = self
.handles
.timer_driver
.as_ref()
.map_or_else(wall_clock_now, TimerDriverHandle::now);
timeout(now, duration, race_fut)
.await
.unwrap_or_else(|_| Err(JoinError::Cancelled(CancelReason::timeout())))
}
/// Races multiple named futures with a timeout.
///
/// # Cancellation vs Draining
///
/// This method **drops** the losing futures (or all futures on timeout),
/// which cancels them. However, it does not await the losers to ensure
/// they have fully cleaned up ("drained").
pub async fn race_timeout_named<T>(
&self,
duration: Duration,
futures: NamedFutures<T>,
) -> Result<T, JoinError>
where
Caps: cap::HasTime,
{
let futures: Vec<_> = futures.into_iter().map(|(_, f)| f).collect();
self.race_timeout(duration, futures).await
}
/// Creates a [`Scope`](super::Scope) bound to this context's region.
///
/// The returned `Scope` can be used to spawn tasks, create child regions,
/// and register finalizers. All spawned tasks will be owned by this
/// context's region.
///
/// # Example
///
/// ```ignore
/// // Using the scope! macro (recommended):
/// scope!(cx, {
/// let handle = scope.spawn(|cx| async { 42 });
/// handle.await
/// });
///
/// // Manual scope creation:
/// let scope = cx.scope();
/// // Use scope for spawning...
/// ```
///
/// # Note
///
/// In Phase 0, this creates a scope bound to the current region. In later
/// phases, the `scope!` macro will create child regions with proper
/// quiescence guarantees.
#[must_use]
pub fn scope(&self) -> crate::cx::Scope<'static> {
let budget = self.budget();
debug!(
task_id = ?self.task_id(),
region_id = ?self.region_id(),
budget_deadline = ?budget.deadline,
budget_poll_quota = budget.poll_quota,
budget_cost_quota = ?budget.cost_quota,
budget_priority = budget.priority,
budget_source = "inherited",
"scope budget inherited"
);
crate::cx::Scope::new_with_capability_budget(
self.region_id(),
budget,
self.capability_budget(),
)
}
/// Creates a [`Scope`](super::Scope) bound to this context's region with a custom budget.
///
/// This is used by the `scope!` macro when a budget is specified:
/// ```ignore
/// scope!(cx, budget: Budget::with_deadline_secs(5), {
/// // body
/// })
/// ```
#[must_use]
pub fn scope_with_budget(&self, budget: Budget) -> crate::cx::Scope<'static> {
let parent_budget = self.budget();
let deadline_tightened = match (parent_budget.deadline, budget.deadline) {
(Some(parent), Some(child)) => child < parent,
(None, Some(_)) => true,
_ => false,
};
let poll_tightened = budget.poll_quota < parent_budget.poll_quota;
let cost_tightened = match (parent_budget.cost_quota, budget.cost_quota) {
(Some(parent), Some(child)) => child < parent,
(None, Some(_)) => true,
_ => false,
};
let priority_boosted = budget.priority > parent_budget.priority;
let _ = (
&deadline_tightened,
&poll_tightened,
&cost_tightened,
&priority_boosted,
);
// Clamp child budget to parent constraints (structured concurrency
// invariant: child regions cannot exceed parent resource limits).
// Priority is intentionally unclamped — boosting is allowed.
let clamped_deadline = match (parent_budget.deadline, budget.deadline) {
(Some(parent), Some(child)) => Some(if child < parent { child } else { parent }),
(Some(parent), None) => Some(parent),
(None, child) => child,
};
let clamped_poll_quota = budget.poll_quota.min(parent_budget.poll_quota);
let clamped_cost_quota = match (parent_budget.cost_quota, budget.cost_quota) {
(Some(parent), Some(child)) => Some(child.min(parent)),
(Some(parent), None) => Some(parent),
(None, child) => child,
};
let clamped = Budget {
deadline: clamped_deadline,
poll_quota: clamped_poll_quota,
cost_quota: clamped_cost_quota,
priority: budget.priority,
};
debug!(
task_id = ?self.task_id(),
region_id = ?self.region_id(),
parent_deadline = ?parent_budget.deadline,
parent_poll_quota = parent_budget.poll_quota,
parent_cost_quota = ?parent_budget.cost_quota,
parent_priority = parent_budget.priority,
budget_deadline = ?clamped.deadline,
budget_poll_quota = clamped.poll_quota,
budget_cost_quota = ?clamped.cost_quota,
budget_priority = clamped.priority,
deadline_tightened,
poll_tightened,
cost_tightened,
priority_boosted,
budget_source = "explicit",
"scope budget set"
);
crate::cx::Scope::new_with_capability_budget(
self.region_id(),
clamped,
self.capability_budget(),
)
}
/// Creates a [`Scope`](super::Scope) with explicit scheduler and
/// capability budgets.
///
/// The scheduler budget is clamped with [`Budget::meet`] semantics by
/// [`Self::scope_with_budget`]. The capability budget is planned against
/// the context's current capability envelope and fails closed when a
/// required dimension is absent or exhausted.
pub fn scope_with_budget_and_capability_budget(
&self,
budget: Budget,
capability_budget: CapabilityBudget,
requirements: CapabilityBudgetRequirements,
) -> Result<crate::cx::Scope<'static>, CapabilityBudgetRefusal> {
let scope = self.scope_with_budget(budget);
let effective = self.plan_child_capability_budget(capability_budget, requirements)?;
Ok(crate::cx::Scope::new_with_capability_budget(
scope.region_id(),
scope.budget(),
effective,
))
}
}
impl Cx<cap::None> {
/// Creates a detached context that carries cancellation and budget state
/// but no runtime effect capabilities.
///
/// This is for adapters and CLI diagnostics that need to exercise
/// cancellation-aware primitives outside a running task. It deliberately
/// returns `Cx<cap::None>` and installs an empty runtime capability mask, so
/// it cannot provide spawn, timer, random, I/O, or remote authority. The
/// synthetic IDs are non-root so an accidental immediate-completion path
/// cannot create a root-scoped obligation.
#[must_use]
pub fn detached_cancel_context() -> Self {
let mut cx = Self::new(
RegionId::from_arena(ArenaIndex::new(1, 1)),
TaskId::from_arena(ArenaIndex::new(1, 1)),
Budget::INFINITE,
);
cx.runtime_mask = cap::CapMask::none();
cx
}
}
impl Cx<cap::All> {
/// Creates a capability context for testing purposes.
///
/// This constructor creates a Cx with default IDs and an infinite budget,
/// suitable for unit and integration tests. The resulting context is fully
/// functional but not connected to a real runtime.
///
/// # Example
///
/// ```
/// use asupersync::Cx;
///
/// let cx = Cx::for_testing();
/// assert!(!cx.is_cancel_requested());
/// assert!(cx.checkpoint().is_ok());
/// ```
///
/// # Note
///
/// This API is intended for testing only. Production code should receive
/// Cx instances from the runtime, not construct them directly.
///
/// # Visibility (br-asupersync-2x6hbi)
///
/// Gated behind `#[cfg(any(test, feature = "test-internals"))]` so that
/// production consumers of the asupersync crate cannot construct a
/// `Cx<cap::All>` out of band, bypassing runtime cap-mask enforcement.
/// Tests still see the constructor through `cfg(test)`, and explicit
/// dev-time consumers can opt in with `--features test-internals`.
#[cfg(any(test, feature = "test-internals"))]
#[must_use]
pub fn for_testing() -> Self {
Self::new(
RegionId::new_for_test(0, 0),
TaskId::new_for_test(0, 0),
Budget::INFINITE,
)
}
/// Creates a test-only capability context with a specified budget.
///
/// Similar to [`Self::for_testing()`] but allows specifying a custom budget
/// for testing timeout behavior.
///
/// # Example
///
/// ```ignore
/// use asupersync::{Cx, Budget, Time};
///
/// // Create a context with a 30-second deadline
/// let cx = Cx::for_testing_with_budget(
/// Budget::new().with_deadline(Time::from_secs(30))
/// );
/// ```
///
/// # Note
///
/// This API is intended for testing only. Production code should receive
/// Cx instances from the runtime, not construct them directly.
/// Gated behind `cfg(any(test, feature = "test-internals"))`
/// (br-asupersync-2x6hbi).
#[cfg(any(test, feature = "test-internals"))]
#[must_use]
pub fn for_testing_with_budget(budget: Budget) -> Self {
Self::new(
RegionId::new_for_test(0, 0),
TaskId::new_for_test(0, 0),
budget,
)
}
/// Creates a test-only capability context with lab I/O capability.
///
/// This constructor creates a Cx with a `LabIoCap` for testing I/O code paths
/// without performing real I/O.
///
/// # Example
///
/// ```ignore
/// use asupersync::Cx;
///
/// let cx = Cx::for_testing_with_io();
/// assert!(cx.has_io());
/// assert!(!cx.io().unwrap().is_real_io());
/// ```
///
/// # Note
///
/// This API is intended for testing only. Gated behind
/// `cfg(any(test, feature = "test-internals"))` (br-asupersync-2x6hbi).
#[cfg(any(test, feature = "test-internals"))]
#[must_use]
pub fn for_testing_with_io() -> Self {
Self::new_with_io(
RegionId::new_for_test(0, 0),
TaskId::new_for_test(0, 0),
Budget::INFINITE,
None,
None,
Some(Arc::new(crate::io::LabIoCap::new_for_tests())),
None,
)
}
/// Creates a request-scoped capability context with a specified budget.
///
/// br-asupersync-ovztin: this constructor is now gated behind
/// `cfg(any(test, feature = "test-internals"))`. The pre-fix shape
/// was fully `pub` and produced a Cx with `CapMask::all()` and
/// freshly-minted ephemeral region/task IDs — i.e. **a fully
/// ambient capability source available to any caller in any
/// crate**. The doc comment claimed the resulting Cx "still
/// carries the runtime cap-mask, so it cannot escalate beyond
/// what the request handler was granted at the boundary"; that
/// claim was false because [`Cx::new`] -> [`Cx::new_with_drivers`]
/// constructed the runtime_mask as `CapMask::all()` without
/// looking at any parent Cx.
///
/// Concrete escape paths the previous shape allowed:
///
/// * **External-crate capability injection.** Any crate linking
/// asupersync could call `Cx::for_request_with_budget(Budget::
/// INFINITE)` from a Drop impl, panic handler, or sync helper
/// and get full Time / IO / blocking-pool / entropy /
/// remote_cap access.
/// * **Sandbox escape from restricted Cx.** A handler holding a
/// mask-narrowed Cx could call this to mint a fresh
/// all-capabilities Cx and bypass the restriction entirely.
/// * **Compounds with br-asupersync-3lk5n2 (now closed): the
/// ephemeral task is also not in `state.tasks`, so oracles /
/// deadline monitor / futurelock detector all silently miss
/// the request.
///
/// Production callers that need a request-scoped Cx must go
/// through [`crate::runtime::Runtime::request_cx_with_budget`],
/// which inherits the runtime's drivers and cap-mask via
/// `build_request_cx_from_inner` and is therefore non-escalating.
///
/// Default builds exclude `test-internals`, so production
/// consumers lose access to this constructor entirely unless they
/// opt in explicitly. The only ambient-free way to mint a Cx in
/// production is through the runtime boundary, which is
/// capability-controlled.
#[cfg(any(test, feature = "test-internals"))]
#[must_use]
pub fn for_request_with_budget(budget: Budget) -> Self {
Self::new(RegionId::new_ephemeral(), TaskId::new_ephemeral(), budget)
}
/// Creates a request-scoped capability context with an infinite budget.
///
/// br-asupersync-ovztin: see [`Self::for_request_with_budget`] for
/// the cfg-gating rationale; this is the infinite-budget convenience
/// wrapper and is gated identically.
#[cfg(any(test, feature = "test-internals"))]
#[must_use]
pub fn for_request() -> Self {
Self::for_request_with_budget(Budget::INFINITE)
}
/// Creates a test-only capability context with a remote capability.
///
/// This constructor creates a Cx with a [`RemoteCap`] for testing remote
/// task spawning without a real network transport.
///
/// # Note
///
/// This API is intended for testing only. Gated behind
/// `cfg(any(test, feature = "test-internals"))` (br-asupersync-2x6hbi).
#[cfg(any(test, feature = "test-internals"))]
#[must_use]
pub fn for_testing_with_remote(cap: RemoteCap) -> Self {
let mut cx = Self::for_testing();
Arc::make_mut(&mut cx.handles).remote_cap = Some(Arc::new(cap));
cx
}
}
/// RAII guard returned by [`Cx::enter_span`].
///
/// On drop, restores the previous `DiagnosticContext` and emits a
/// span-exit log entry.
pub struct SpanGuard<Caps = cap::All> {
cx: Cx<Caps>,
prev: DiagnosticContext,
}
impl<Caps> Drop for SpanGuard<Caps> {
fn drop(&mut self) {
let name = self
.cx
.diagnostic_context()
.custom("span.name")
.unwrap_or("unknown")
.to_owned();
self.cx
.log(LogEntry::debug(format!("span exit: {name}")).with_target("tracing"));
self.cx.set_diagnostic_context(self.prev.clone());
}
}
#[cfg(test)]
mod tests {
#![allow(
clippy::pedantic,
clippy::nursery,
clippy::expect_fun_call,
clippy::map_unwrap_or,
clippy::cast_possible_wrap,
clippy::future_not_send
)]
use super::*;
use crate::cx::macaroon::CaveatPredicate;
#[cfg(feature = "messaging-fabric")]
use crate::messaging::capability::{CommandFamily, FabricCapability, FabricCapabilityScope};
#[cfg(feature = "messaging-fabric")]
use crate::messaging::class::DeliveryClass;
#[cfg(feature = "messaging-fabric")]
use crate::messaging::ir::{CapabilityPermission, CapabilityTokenSchema, SubjectFamily};
#[cfg(feature = "messaging-fabric")]
use crate::messaging::subject::SubjectPattern;
use crate::trace::TraceBufferHandle;
use crate::types::CapabilityBudgetDimension;
use crate::util::{ArenaIndex, DetEntropy};
use std::sync::atomic::{AtomicU8, Ordering};
static CURRENT_CX_DTOR_STATE: AtomicU8 = AtomicU8::new(0);
thread_local! {
static CURRENT_CX_DTOR_PROBE: CurrentCxDtorProbe = const { CurrentCxDtorProbe };
}
struct CurrentCxDtorProbe;
impl Drop for CurrentCxDtorProbe {
fn drop(&mut self) {
let state = if Cx::is_active() {
1
} else if Cx::current().is_some() {
2
} else {
3
};
CURRENT_CX_DTOR_STATE.store(state as u8, Ordering::SeqCst);
}
}
fn test_cx() -> Cx<cap::All> {
Cx::for_testing()
}
fn test_cx_with_entropy(seed: u64) -> Cx<cap::All> {
Cx::new_with_observability(
RegionId::new_for_test(0, 0),
TaskId::new_for_test(0, 0),
Budget::INFINITE,
None,
None,
Some(Arc::new(DetEntropy::new(seed))),
)
}
fn trace_message(event: &crate::trace::TraceEvent) -> &str {
match &event.data {
crate::trace::TraceData::Message(message) => message,
other => panic!("expected user trace message, got {other:?}"),
}
}
#[cfg(feature = "messaging-fabric")]
fn capability_schema(
families: Vec<SubjectFamily>,
permissions: Vec<CapabilityPermission>,
) -> CapabilityTokenSchema {
CapabilityTokenSchema {
name: "fabric.cx.demo".to_owned(),
families,
delivery_classes: vec![DeliveryClass::EphemeralInteractive],
permissions,
}
}
#[test]
fn io_not_available_by_default() {
let cx = test_cx();
assert!(!cx.has_io());
assert!(cx.io().is_none());
}
/// br-asupersync-xqt7dj: with_current(f) must invoke f with a borrowed
/// &Cx that observes the SAME runtime mask as the legacy Cx::current()
/// would have observed under set_current_restricted, AND in the
/// unrestricted common case must NOT bump any Arc strong count of the
/// installed cx (zero-clone fast path).
#[test]
fn with_current_zero_clone_in_unrestricted_case() {
let cx = test_cx();
// Reference strong counts BEFORE installation as ambient.
let _guard = Cx::set_current(Some(cx.clone()));
// Capture strong counts of the installed-frame's inner Arcs.
let frame_inner_strong_before =
Arc::strong_count(&Cx::current().expect("current should resolve").inner.clone());
// current() itself bumped the count by +1 above (we cloned to read);
// hold a 2nd reference to keep the count stable across with_current.
let cx_pin = Cx::current().expect("current");
let baseline = Arc::strong_count(&cx_pin.inner);
let observed = Cx::with_current(|borrowed| {
// Inside the closure, while we hold the borrow, the inner
// strong count must NOT have been incremented above baseline.
// This proves the zero-clone fast path was taken.
let count_during_borrow = Arc::strong_count(&borrowed.inner);
(count_during_borrow, borrowed.runtime_mask)
})
.expect("with_current should invoke closure");
// The fast path borrows frame.cx directly without Arc::clone, so
// the inner strong count during the borrow equals baseline.
assert_eq!(
observed.0, baseline,
"with_current must not bump inner.strong_count in unrestricted case"
);
// Mask must reflect the installed frame (full caps for set_current).
assert_eq!(observed.1, cap::CapMask::all());
let _ = frame_inner_strong_before;
}
/// br-asupersync-xqt7dj: with_current must apply the frame's narrowed
/// mask when set_current_restricted is active. In the restricted case
/// the implementation falls back to clone+overlay (3 Arc::clone) to
/// preserve the security invariant from br-asupersync-5ckssb; verify
/// the closure observes the narrow mask.
#[test]
fn with_current_applies_restriction_mask() {
let cx = test_cx();
// restricted_cx with NoCaps narrows the runtime mask.
let restricted = cx.clone().restrict::<cap::None>();
let _guard = restricted.set_current_restricted();
let mask_seen = Cx::with_current(|borrowed| borrowed.runtime_mask)
.expect("with_current should resolve under restricted scope");
assert_eq!(
mask_seen,
cap::CapMask::none(),
"with_current must apply the frame's narrowed mask"
);
}
/// br-asupersync-xqt7dj: with_current returns None when no ambient cx
/// is installed; the closure must NOT fire.
#[test]
fn with_current_returns_none_when_no_ambient() {
let mut closure_ran = false;
let result = Cx::with_current(|_cx| {
closure_ran = true;
42_u32
});
assert!(result.is_none());
assert!(
!closure_ran,
"closure must not be invoked when no ambient cx is installed"
);
}
#[test]
fn io_available_with_for_testing_with_io() {
let cx: Cx = Cx::for_testing_with_io();
assert!(cx.has_io());
let io = cx.io().expect("should have io cap");
assert!(!io.is_real_io());
assert_eq!(io.name(), "lab");
}
#[test]
fn checkpoint_without_cancel() {
let cx = test_cx();
assert!(cx.checkpoint().is_ok());
}
#[test]
fn checkpoint_with_cancel() {
let cx = test_cx();
cx.set_cancel_requested(true);
assert!(cx.checkpoint().is_err());
}
#[test]
fn masked_defers_cancel() {
let cx = test_cx();
cx.set_cancel_requested(true);
cx.masked(|| {
assert!(
cx.checkpoint().is_ok(),
"checkpoint should succeed when masked"
);
});
assert!(
cx.checkpoint().is_err(),
"checkpoint should fail after unmasking"
);
}
#[test]
fn trace_attaches_logical_time() {
let cx = test_cx();
let trace = TraceBufferHandle::new(8);
cx.set_trace_buffer(trace.clone());
cx.trace("hello");
let events = trace.snapshot();
let event = events.first().expect("trace event");
assert!(event.logical_time.is_some());
}
#[test]
fn masked_panic_safety() {
use std::panic::{AssertUnwindSafe, catch_unwind};
let cx = test_cx();
cx.set_cancel_requested(true);
// Ensure initial state is cancelled (unmasked)
assert!(cx.checkpoint().is_err());
// Run a masked block that panics
let cx_clone = cx.clone();
let _ = catch_unwind(AssertUnwindSafe(|| {
cx_clone.masked(|| {
// Avoid `panic!/unreachable!` macros (UBS critical). We still
// need an unwind here to validate mask-depth restoration.
std::panic::resume_unwind(Box::new("oops"));
});
}));
// After panic, mask depth should have been restored.
// If it leaked, checkpoint() will return Ok(()) because it thinks it's still masked.
assert!(
cx.checkpoint().is_err(),
"Cx remains masked after panic! mask_depth leaked."
);
}
#[test]
fn current_returns_none_during_thread_local_teardown() {
CURRENT_CX_DTOR_STATE.store(0, Ordering::SeqCst);
let join = std::thread::spawn(|| {
// Initialize the probe first so its destructor runs after CURRENT_CX
// and exercises ambient lookup during TLS teardown.
CURRENT_CX_DTOR_PROBE.with(|_| {});
let cx = test_cx();
let _guard = Cx::set_current(Some(cx));
assert!(Cx::is_active(), "current cx should be installed");
});
join.join()
.expect("thread-local teardown should not panic when reading Cx");
assert_eq!(
CURRENT_CX_DTOR_STATE.load(Ordering::SeqCst),
3,
"Cx::current() should fail closed once CURRENT_CX is unavailable"
);
}
/// INV-MASK-BOUNDED: exceeding MAX_MASK_DEPTH must panic.
#[test]
#[should_panic(expected = "MAX_MASK_DEPTH")]
fn mask_depth_exceeds_bound_panics() {
let cx = test_cx();
// Directly set mask_depth to the limit, then call masked() once
// to trigger the bound check. This avoids deep nesting which
// would cause double-panic in MaskGuard drops during unwind.
{
let mut inner = cx.inner.write();
inner.mask_depth = crate::types::task_context::MAX_MASK_DEPTH;
}
// This call should panic because mask_depth is already at the limit.
cx.masked(|| {});
}
/// Context stack depth must be bounded to prevent stack overflow.
#[test]
#[should_panic(expected = "MAX_CONTEXT_STACK_DEPTH")]
fn context_stack_depth_exceeds_bound_panics_set_current() {
let cx = test_cx();
// Fill the context stack to the limit manually to avoid deep nesting
// during test setup that could cause issues during panic unwinding.
CURRENT_CX_STACK.with(|stack| {
let mut s = stack.borrow_mut();
for _ in 0..crate::types::task_context::MAX_CONTEXT_STACK_DEPTH {
s.push(CurrentCxFrame {
cx: cx.clone().retype::<cap::All>(),
mask: cap::CapMask::all(),
});
}
});
// This call should panic because stack is already at the limit.
let _guard = cx.set_current_restricted();
}
/// Context stack depth must be bounded to prevent stack overflow (push_restriction variant).
#[test]
#[should_panic(expected = "MAX_CONTEXT_STACK_DEPTH")]
fn context_stack_depth_exceeds_bound_panics_push_restriction() {
let cx = test_cx();
let _guard = Cx::set_current(Some(cx.clone()));
// Fill the context stack to the limit manually to avoid deep nesting
CURRENT_CX_STACK.with(|stack| {
let mut s = stack.borrow_mut();
for _ in 0..crate::types::task_context::MAX_CONTEXT_STACK_DEPTH {
s.push(CurrentCxFrame {
cx: cx.clone().retype::<cap::All>(),
mask: cap::CapMask::all(),
});
}
});
// This call should panic because stack is already at the limit.
let _restriction_guard = FullCx::push_restriction(cap::CapMask::none());
}
#[test]
fn random_usize_in_range() {
let cx = test_cx_with_entropy(123);
for _ in 0..100 {
let value = cx.random_usize(7);
assert!(value < 7);
}
}
#[test]
fn shuffle_deterministic() {
let cx1 = test_cx_with_entropy(42);
let cx2 = test_cx_with_entropy(42);
let mut a = [1, 2, 3, 4, 5, 6, 7, 8];
let mut b = [1, 2, 3, 4, 5, 6, 7, 8];
cx1.shuffle(&mut a);
cx2.shuffle(&mut b);
assert_eq!(a, b);
}
#[test]
fn random_f64_range() {
let cx = test_cx_with_entropy(7);
for _ in 0..100 {
let value = cx.random_f64();
assert!((0.0..1.0).contains(&value));
}
}
/// br-asupersync-lw9q66: random_u64 must NOT include the random
/// value in its trace event. The static-source proof is the
/// commit comment + the trace! call shape; this test pins the
/// runtime behaviour by asserting the function still returns
/// distinct values and matches the same per-seed output as
/// before the trace change (so no semantic regression accompanied
/// the log-shape fix).
#[test]
fn lw9q66_random_u64_returns_distinct_values_without_logging_value() {
let cx = test_cx_with_entropy(0xdead_beef);
let mut samples = std::collections::HashSet::new();
for _ in 0..256 {
samples.insert(cx.random_u64());
}
// 256 samples from a CSPRNG: expect at least 200 unique to
// confirm the source is producing varied output (not stuck).
assert!(
samples.len() >= 200,
"random_u64 must produce varied output (got {} unique of 256)",
samples.len()
);
// Determinism check: a fresh cx with the same seed should
// produce the same first value (proves seed propagation
// isn't perturbed by the trace-shape change).
let cx2 = test_cx_with_entropy(0xdead_beef);
let cx3 = test_cx_with_entropy(0xdead_beef);
assert_eq!(cx2.random_u64(), cx3.random_u64());
}
// ========================================================================
// Cancel Attribution API Tests
// ========================================================================
#[test]
fn cancel_with_sets_reason() {
let cx = test_cx();
assert!(cx.cancel_reason().is_none());
cx.cancel_with(CancelKind::User, Some("manual stop"));
assert!(cx.is_cancel_requested());
let reason = cx.cancel_reason().expect("should have reason");
assert_eq!(reason.kind, CancelKind::User);
assert_eq!(reason.message, Some("manual stop".to_string()));
}
#[test]
fn cancel_with_no_message() {
let cx = test_cx();
cx.cancel_with(CancelKind::Timeout, None);
let reason = cx.cancel_reason().expect("should have reason");
assert_eq!(reason.kind, CancelKind::Timeout);
assert!(reason.message.is_none());
}
#[test]
fn cancel_reason_returns_none_when_not_cancelled() {
let cx = test_cx();
assert!(cx.cancel_reason().is_none());
}
#[test]
fn cancel_chain_empty_when_not_cancelled() {
let cx = test_cx();
assert!(cx.cancel_chain().next().is_none());
}
#[test]
fn cancel_chain_traverses_causes() {
let cx = test_cx();
// Build a chain: ParentCancelled -> ParentCancelled -> Deadline
let deadline = CancelReason::deadline();
let parent1 = CancelReason::parent_cancelled().with_cause(deadline);
let parent2 = CancelReason::parent_cancelled().with_cause(parent1);
cx.set_cancel_reason(parent2);
let chain: Vec<_> = cx.cancel_chain().collect();
assert_eq!(chain.len(), 3);
assert_eq!(chain[0].kind, CancelKind::ParentCancelled);
assert_eq!(chain[1].kind, CancelKind::ParentCancelled);
assert_eq!(chain[2].kind, CancelKind::Deadline);
}
#[test]
fn root_cancel_cause_returns_none_when_not_cancelled() {
let cx = test_cx();
assert!(cx.root_cancel_cause().is_none());
}
#[test]
fn root_cancel_cause_finds_root() {
let cx = test_cx();
// Build: ParentCancelled -> Timeout
let timeout = CancelReason::timeout();
let parent = CancelReason::parent_cancelled().with_cause(timeout);
cx.set_cancel_reason(parent);
let root = cx.root_cancel_cause().expect("should have root");
assert_eq!(root.kind, CancelKind::Timeout);
}
#[test]
fn root_cancel_cause_with_no_chain() {
let cx = test_cx();
cx.cancel_with(CancelKind::Shutdown, None);
let root = cx.root_cancel_cause().expect("should have root");
assert_eq!(root.kind, CancelKind::Shutdown);
}
#[test]
fn cancelled_by_checks_immediate_reason() {
let cx = test_cx();
// Build: ParentCancelled -> Deadline
let deadline = CancelReason::deadline();
let parent = CancelReason::parent_cancelled().with_cause(deadline);
cx.set_cancel_reason(parent);
// Immediate reason is ParentCancelled
assert!(cx.cancelled_by(CancelKind::ParentCancelled));
// Deadline is in chain but not immediate
assert!(!cx.cancelled_by(CancelKind::Deadline));
}
#[test]
fn cancelled_by_returns_false_when_not_cancelled() {
let cx = test_cx();
assert!(!cx.cancelled_by(CancelKind::User));
}
#[test]
fn any_cause_is_searches_chain() {
let cx = test_cx();
// Build: ParentCancelled -> ParentCancelled -> Timeout
let timeout = CancelReason::timeout();
let parent1 = CancelReason::parent_cancelled().with_cause(timeout);
let parent2 = CancelReason::parent_cancelled().with_cause(parent1);
cx.set_cancel_reason(parent2);
// All kinds in the chain return true
assert!(cx.any_cause_is(CancelKind::ParentCancelled));
assert!(cx.any_cause_is(CancelKind::Timeout));
// Kinds not in chain return false
assert!(!cx.any_cause_is(CancelKind::Deadline));
assert!(!cx.any_cause_is(CancelKind::Shutdown));
}
#[test]
fn any_cause_is_returns_false_when_not_cancelled() {
let cx = test_cx();
assert!(!cx.any_cause_is(CancelKind::Timeout));
}
#[test]
fn set_cancel_reason_sets_flag_and_reason() {
let cx = test_cx();
assert!(!cx.is_cancel_requested());
cx.set_cancel_reason(CancelReason::shutdown());
assert!(cx.is_cancel_requested());
assert_eq!(
cx.cancel_reason().expect("should have reason").kind,
CancelKind::Shutdown
);
}
#[test]
fn integration_realistic_usage() {
// Simulate a realistic cancellation scenario:
// 1. Root region times out
// 2. Child task receives ParentCancelled
// 3. Handler inspects the cause chain
let cx = test_cx();
// Simulate runtime setting a chained reason (timeout -> parent_cancelled)
let timeout_reason = CancelReason::timeout().with_message("request timeout");
let child_reason = CancelReason::parent_cancelled().with_cause(timeout_reason);
cx.set_cancel_reason(child_reason);
// Handler code checks various conditions
assert!(cx.is_cancel_requested());
// Immediate reason is ParentCancelled
assert!(cx.cancelled_by(CancelKind::ParentCancelled));
// But we want to know if a timeout caused it
if cx.any_cause_is(CancelKind::Timeout) {
// Log or metric: "Request cancelled due to timeout"
let root = cx.root_cancel_cause().unwrap();
assert_eq!(root.kind, CancelKind::Timeout);
assert_eq!(root.message, Some("request timeout".to_string()));
}
// Full chain inspection
let chain: Vec<_> = cx.cancel_chain().collect();
assert_eq!(chain.len(), 2);
assert_eq!(chain[0].kind, CancelKind::ParentCancelled);
assert_eq!(chain[1].kind, CancelKind::Timeout);
}
#[test]
fn cancel_fast_sets_flag_and_reason() {
let cx = test_cx();
assert!(!cx.is_cancel_requested());
assert!(cx.cancel_reason().is_none());
cx.cancel_fast(CancelKind::Shutdown);
assert!(cx.is_cancel_requested());
let reason = cx.cancel_reason().expect("should have reason");
assert_eq!(reason.kind, CancelKind::Shutdown);
}
#[test]
fn cancel_fast_no_cause_chain() {
// cancel_fast is for the no-attribution path - it shouldn't create cause chains
let cx = test_cx();
cx.cancel_fast(CancelKind::Timeout);
let reason = cx.cancel_reason().expect("should have reason");
// No cause chain
assert!(reason.cause.is_none());
// No message
assert!(reason.message.is_none());
// Not truncated (nothing to truncate)
assert!(!reason.truncated);
}
#[test]
fn cancel_fast_sets_region() {
let cx = test_cx();
cx.cancel_fast(CancelKind::User);
let reason = cx.cancel_reason().expect("should have reason");
// Region should be set from the Cx
let expected_region = RegionId::from_arena(ArenaIndex::new(0, 0));
assert_eq!(reason.origin_region, expected_region);
}
#[test]
fn cancel_fast_minimal_allocation() {
// cancel_fast should create minimal CancelReason without extra allocations
let cx = test_cx();
cx.cancel_fast(CancelKind::Deadline);
let reason = cx.cancel_reason().expect("should have reason");
// Verify minimal structure: just kind, region, no message, no cause, no truncation
assert_eq!(reason.kind, CancelKind::Deadline);
assert!(reason.message.is_none());
assert!(reason.cause.is_none());
assert!(!reason.truncated);
assert!(reason.truncated_at_depth.is_none());
// Memory cost should be minimal (just the struct size, no boxed cause)
let cost = reason.estimated_memory_cost();
// Should be roughly just the size of CancelReason without any heap allocations for cause
assert!(
cost < 200,
"cancel_fast should have minimal memory cost, got {cost}"
);
}
// ========================================================================
// Checkpoint Progress Reporting Tests
// ========================================================================
#[test]
fn checkpoint_records_progress() {
let cx = test_cx();
// Initially no checkpoints
let state = cx.checkpoint_state();
assert!(state.last_checkpoint.is_none());
assert!(state.last_message.is_none());
assert_eq!(state.checkpoint_count, 0);
// Record first checkpoint
assert!(cx.checkpoint().is_ok());
let state = cx.checkpoint_state();
assert!(state.last_checkpoint.is_some());
assert!(state.last_message.is_none());
assert_eq!(state.checkpoint_count, 1);
// Record second checkpoint
assert!(cx.checkpoint().is_ok());
let state = cx.checkpoint_state();
assert_eq!(state.checkpoint_count, 2);
}
#[test]
fn checkpoint_with_records_message() {
let cx = test_cx();
// Record checkpoint with message
assert!(cx.checkpoint_with("processing step 1").is_ok());
let state = cx.checkpoint_state();
assert!(state.last_checkpoint.is_some());
assert_eq!(state.last_message.as_deref(), Some("processing step 1"));
assert_eq!(state.checkpoint_count, 1);
// Second checkpoint overwrites message
assert!(cx.checkpoint_with("processing step 2").is_ok());
let state = cx.checkpoint_state();
assert_eq!(state.last_message.as_deref(), Some("processing step 2"));
assert_eq!(state.checkpoint_count, 2);
}
#[test]
fn checkpoint_clears_message() {
let cx = test_cx();
// Record checkpoint with message
cx.checkpoint_with("step 1")
.expect("checkpoint_with should succeed");
assert_eq!(
cx.checkpoint_state().last_message.as_deref(),
Some("step 1")
);
// Regular checkpoint clears the message
cx.checkpoint()
.expect("checkpoint should succeed after message set");
assert!(cx.checkpoint_state().last_message.is_none());
}
#[test]
fn checkpoint_with_checks_cancel() {
let cx = test_cx();
cx.set_cancel_requested(true);
// checkpoint_with should return error on cancellation
assert!(cx.checkpoint_with("should fail").is_err());
// But checkpoint state should still be updated
let state = cx.checkpoint_state();
assert_eq!(state.checkpoint_count, 1);
assert_eq!(state.last_message.as_deref(), Some("should fail"));
}
#[test]
fn checkpoint_deadline_exhaustion_sets_cancel_reason() {
let cx = Cx::for_testing_with_budget(Budget::new().with_deadline(Time::ZERO));
assert!(cx.checkpoint().is_err());
let reason = cx
.cancel_reason()
.expect("deadline exhaustion must set reason");
assert_eq!(reason.kind, CancelKind::Deadline);
assert!(cx.is_cancel_requested());
}
#[test]
fn checkpoint_poll_budget_exhaustion_sets_cancel_reason() {
let cx = Cx::for_testing_with_budget(Budget::new().with_poll_quota(0));
assert!(cx.checkpoint().is_err());
let reason = cx
.cancel_reason()
.expect("poll quota exhaustion must set reason");
assert_eq!(reason.kind, CancelKind::PollQuota);
assert!(cx.is_cancel_requested());
}
#[test]
fn checkpoint_cost_budget_exhaustion_sets_cancel_reason() {
let cx = Cx::for_testing_with_budget(Budget::new().with_cost_quota(0));
assert!(cx.checkpoint().is_err());
let reason = cx
.cancel_reason()
.expect("cost budget exhaustion must set reason");
assert_eq!(reason.kind, CancelKind::CostBudget);
assert!(cx.is_cancel_requested());
}
#[test]
fn capability_budget_plan_inherits_and_tightens() {
let cx = test_cx();
let parent = CapabilityBudget::new()
.with_memory_bytes(1_024)
.with_io_bytes(4_096)
.with_cleanup_budget(Budget::new().with_poll_quota(100_000));
let requirements = CapabilityBudgetRequirements::new()
.require_memory_bytes()
.require_io_bytes()
.require_cleanup();
cx.apply_child_capability_budget(parent, requirements)
.expect("parent capability budget is complete");
let child = CapabilityBudget::new()
.with_memory_bytes(2_048)
.with_io_bytes(512)
.with_cleanup_budget(Budget::new().with_poll_quota(100_000));
let effective = cx
.plan_child_capability_budget(child, requirements)
.expect("child should inherit missing required envelopes");
assert_eq!(effective.memory_bytes, Some(1_024));
assert_eq!(effective.io_bytes, Some(512));
assert_eq!(
effective.cleanup_budget.map(|budget| budget.poll_quota),
Some(100_000)
);
assert_eq!(cx.capability_budget(), parent);
}
#[test]
fn capability_budget_apply_fails_closed_when_required_missing() {
let cx = test_cx();
let requirements = CapabilityBudgetRequirements::new().require_artifact_bytes();
let err = cx
.apply_child_capability_budget(CapabilityBudget::new(), requirements)
.expect_err("missing artifact budget must fail closed");
assert_eq!(
err,
CapabilityBudgetRefusal::MissingRequired(CapabilityBudgetDimension::ArtifactBytes)
);
assert_eq!(cx.capability_budget(), CapabilityBudget::UNSPECIFIED);
}
#[test]
fn scope_inherits_cx_capability_budget() {
let cx = test_cx();
let budget = CapabilityBudget::new()
.with_memory_bytes(2_048)
.with_cpu_units(32);
cx.apply_child_capability_budget(budget, CapabilityBudgetRequirements::NONE)
.expect("optional capability budget should apply");
let scope = cx.scope();
assert_eq!(scope.capability_budget(), budget);
}
#[test]
fn scope_with_capability_budget_fails_closed_when_required_missing() {
let cx = test_cx();
let err = cx
.scope_with_budget_and_capability_budget(
Budget::INFINITE,
CapabilityBudget::new(),
CapabilityBudgetRequirements::new().require_artifact_bytes(),
)
.expect_err("missing artifact envelope must fail closed");
assert_eq!(
err,
CapabilityBudgetRefusal::MissingRequired(CapabilityBudgetDimension::ArtifactBytes)
);
}
#[test]
fn masked_checkpoint_defers_budget_exhaustion() {
let cx = Cx::for_testing_with_budget(Budget::new().with_deadline(Time::ZERO));
cx.masked(|| {
assert!(
cx.checkpoint().is_ok(),
"budget exhaustion should defer while masked"
);
});
let reason = cx
.cancel_reason()
.expect("masked checkpoint should still record exhaustion reason");
assert_eq!(reason.kind, CancelKind::Deadline);
assert!(
cx.checkpoint().is_err(),
"deadline exhaustion should be observed after unmasking"
);
}
#[test]
fn checkpoint_budget_usage_reports_remaining_time_in_millis() {
let budget = Budget::new()
.with_deadline(Time::from_secs(10))
.with_poll_quota(3)
.with_cost_quota(7);
let baseline = Budget::new()
.with_deadline(Time::from_secs(20))
.with_poll_quota(5)
.with_cost_quota(11);
let (polls_used, cost_used, time_remaining_ms) =
Cx::<cap::All>::checkpoint_budget_usage(budget, baseline, Time::from_secs(7));
assert_eq!(polls_used, Some(2));
assert_eq!(cost_used, Some(4));
assert_eq!(time_remaining_ms, Some(3_000));
}
#[test]
fn set_cancel_requested_wakes_registered_cancel_waker() {
use std::sync::atomic::{AtomicUsize, Ordering};
use std::task::Waker;
struct CountWaker(Arc<AtomicUsize>);
use std::task::Wake;
impl Wake for CountWaker {
fn wake(self: Arc<Self>) {
self.0.fetch_add(1, Ordering::SeqCst);
}
fn wake_by_ref(self: &Arc<Self>) {
self.0.fetch_add(1, Ordering::SeqCst);
}
}
let cx = test_cx();
let wakes = Arc::new(AtomicUsize::new(0));
let waker = Waker::from(Arc::new(CountWaker(Arc::clone(&wakes))));
{
let mut inner = cx.inner.write();
inner.cancel_waker = Some(waker);
}
cx.set_cancel_requested(true);
assert_eq!(
wakes.load(Ordering::SeqCst),
1,
"set_cancel_requested(true) must wake the registered cancel waker"
);
cx.set_cancel_requested(false);
assert_eq!(
wakes.load(Ordering::SeqCst),
1,
"clearing cancellation must not spuriously wake the cancel waker"
);
}
#[test]
fn checkpoint_state_is_snapshot() {
let cx = test_cx();
// Get a snapshot
let snapshot = cx.checkpoint_state();
assert_eq!(snapshot.checkpoint_count, 0);
// Record more checkpoints
assert!(cx.checkpoint().is_ok());
assert!(cx.checkpoint().is_ok());
// Original snapshot should be unchanged
assert_eq!(snapshot.checkpoint_count, 0);
// New snapshot should reflect updates
assert_eq!(cx.checkpoint_state().checkpoint_count, 2);
}
#[test]
fn checkpoint_with_accepts_string_types() {
let cx = test_cx();
// Test &str
assert!(cx.checkpoint_with("literal").is_ok());
// Test String
assert!(cx.checkpoint_with(String::from("owned")).is_ok());
// Test format!
assert!(cx.checkpoint_with(format!("item {}", 42)).is_ok());
assert_eq!(cx.checkpoint_state().checkpoint_count, 3);
}
// -----------------------------------------------------------------
// Macaroon integration tests (bd-2lqyk.2)
// -----------------------------------------------------------------
fn test_root_key() -> crate::security::key::AuthKey {
crate::security::key::AuthKey::from_seed(42)
}
#[test]
fn cx_no_macaroon_by_default() {
let cx = test_cx();
assert!(cx.macaroon().is_none());
}
#[test]
fn cx_with_macaroon_attaches_token() {
let key = test_root_key();
let token = MacaroonToken::mint(&key, "spawn:r1", "cx/scheduler");
let cx = test_cx().with_macaroon(token);
let m = cx.macaroon().expect("should have macaroon");
assert_eq!(m.identifier(), "spawn:r1");
assert_eq!(m.location(), "cx/scheduler");
}
#[test]
fn cx_macaroon_survives_clone() {
let key = test_root_key();
let token = MacaroonToken::mint(&key, "io:net", "cx/io");
let cx = test_cx().with_macaroon(token);
let cx2 = cx.clone();
assert_eq!(
cx.macaroon()
.expect("cx should have macaroon after with_macaroon")
.identifier(),
cx2.macaroon()
.expect("cloned cx should have macaroon")
.identifier()
);
// Test attenuation to verify the attenuation mechanism works
let attenuated_cx = cx
.attenuate(CaveatPredicate::TimeBefore(u64::MAX / 2))
.expect("attenuation should succeed");
assert!(
attenuated_cx
.macaroon()
.expect("attenuated cx should have macaroon")
.is_direct_attenuation_of(
cx.macaroon()
.expect("cx should have macaroon for attenuation check"),
&CaveatPredicate::TimeBefore(u64::MAX / 2)
),
"Cx::attenuate must install only a direct child of the parent token"
);
}
#[test]
fn cx_macaroon_survives_restrict() {
let key = test_root_key();
let token = MacaroonToken::mint(&key, "all:cap", "cx/root");
let cx: Cx<cap::All> = test_cx().with_macaroon(token);
let narrow: Cx<cap::None> = cx.restrict();
assert_eq!(
cx.macaroon().expect("cx should have macaroon").identifier(),
narrow
.macaroon()
.expect("narrow should have macaroon")
.identifier()
);
}
#[test]
fn cx_attenuate_adds_caveat() {
let key = test_root_key();
let token = MacaroonToken::mint(&key, "spawn:r1", "cx/scheduler");
let cx = test_cx().with_macaroon(token);
let cx2 = cx
.attenuate(CaveatPredicate::TimeBefore(u64::MAX / 2))
.expect("attenuate should succeed");
// Original unchanged
assert_eq!(
cx.macaroon()
.expect("cx should have macaroon")
.caveat_count(),
0
);
// Attenuated has one caveat
assert_eq!(
cx2.macaroon()
.expect("cx2 should have macaroon")
.caveat_count(),
1
);
// Both share the same identifier
assert_eq!(
cx.macaroon().expect("cx should have macaroon").identifier(),
cx2.macaroon()
.expect("cx2 should have macaroon")
.identifier()
);
}
#[test]
fn cx_attenuate_returns_none_without_macaroon() {
let cx = test_cx();
assert!(cx.attenuate(CaveatPredicate::MaxUses(10)).is_none());
}
#[test]
fn cx_attenuate_scope_rejects_oversized_pattern() {
let key = test_root_key();
let token = MacaroonToken::mint(&key, "spawn:r1", "cx/scheduler");
let cx = test_cx().with_macaroon(token);
let pattern = "x".repeat(u16::MAX as usize + 1);
let attenuated = cx.attenuate_scope(pattern);
assert!(
attenuated.is_none(),
"oversized caveat content must fail closed instead of reaching the encoder"
);
assert_eq!(
cx.macaroon()
.expect("cx should have macaroon")
.caveat_count(),
0
);
}
#[test]
fn cx_attenuate_from_budget_returns_none_without_macaroon() {
let cx = test_cx();
assert!(cx.attenuate_from_budget().is_none());
}
#[test]
fn cx_attenuate_from_budget_preserves_token_without_deadline() {
let key = test_root_key();
let token = MacaroonToken::mint(&key, "spawn:r1", "cx/scheduler");
let cx = test_cx().with_macaroon(token);
let attenuated = cx
.attenuate_from_budget()
.expect("macaroon should still be present");
assert_eq!(
attenuated
.macaroon()
.expect("attenuated should have macaroon")
.caveat_count(),
0
);
assert_eq!(
attenuated
.macaroon()
.expect("attenuated should have macaroon")
.identifier(),
cx.macaroon().expect("cx should have macaroon").identifier()
);
}
#[test]
fn cx_attenuate_from_budget_adds_deadline_caveat() {
let key = test_root_key();
let token = MacaroonToken::mint(&key, "spawn:r1", "cx/scheduler");
let budget = Budget::new().with_deadline(Time::from_millis(5_000));
let cx = Cx::for_testing_with_budget(budget).with_macaroon(token);
let attenuated = cx
.attenuate_from_budget()
.expect("attenuation with deadline should succeed");
assert_eq!(
attenuated
.macaroon()
.expect("attenuated should have macaroon")
.caveat_count(),
1
);
}
#[test]
fn cx_verify_capability_succeeds() {
let key = test_root_key();
let token = MacaroonToken::mint(&key, "spawn:r1", "cx/scheduler");
let cx = test_cx().with_macaroon(token);
let ctx = VerificationContext::new().with_time(1000);
assert!(cx.verify_capability(&key, "spawn:r1", &ctx).is_ok());
}
#[test]
fn cx_verify_capability_fails_wrong_key() {
let key = test_root_key();
let wrong_key = crate::security::key::AuthKey::from_seed(99);
let token = MacaroonToken::mint(&key, "spawn:r1", "cx/scheduler");
let cx = test_cx().with_macaroon(token);
let ctx = VerificationContext::new();
let err = cx
.verify_capability(&wrong_key, "spawn:r1", &ctx)
.unwrap_err();
assert!(matches!(err, VerificationError::InvalidSignature));
}
#[test]
fn cx_verify_capability_fails_no_macaroon() {
let key = test_root_key();
let cx = test_cx();
let ctx = VerificationContext::new();
let err = cx.verify_capability(&key, "spawn:r1", &ctx).unwrap_err();
assert!(matches!(err, VerificationError::InvalidSignature));
}
#[test]
fn cx_verify_with_caveats() {
let key = test_root_key();
let token = MacaroonToken::mint(&key, "spawn:r1", "cx/scheduler")
.add_caveat(CaveatPredicate::TimeBefore(5_000))
.add_caveat(CaveatPredicate::RegionScope(42));
let cx = test_cx().with_macaroon(token);
// Passes with correct context
let ctx = VerificationContext::new().with_time(1000).with_region(42);
assert!(cx.verify_capability(&key, "spawn:r1", &ctx).is_ok());
// Fails with expired time
let ctx_expired = VerificationContext::new().with_time(6000).with_region(42);
let err = cx
.verify_capability(&key, "spawn:r1", &ctx_expired)
.unwrap_err();
assert!(matches!(
err,
VerificationError::CaveatFailed { index: 0, .. }
));
// Fails with wrong region
let ctx_wrong_region = VerificationContext::new().with_time(1000).with_region(99);
let err = cx
.verify_capability(&key, "spawn:r1", &ctx_wrong_region)
.unwrap_err();
assert!(matches!(
err,
VerificationError::CaveatFailed { index: 1, .. }
));
}
#[test]
fn cx_attenuate_then_verify() {
let key = test_root_key();
let token = MacaroonToken::mint(&key, "time:sleep", "cx/time");
let cx = test_cx().with_macaroon(token);
// Attenuate with time limit
let cx2 = cx
.attenuate(CaveatPredicate::TimeBefore(3_000))
.expect("attenuation should succeed");
// Further attenuate with max uses
let cx3 = cx2
.attenuate(CaveatPredicate::MaxUses(5))
.expect("second attenuation should succeed");
// Original has no restrictions
let ctx = VerificationContext::new().with_time(1000);
assert!(cx.verify_capability(&key, "time:sleep", &ctx).is_ok());
// cx2 has time restriction
assert!(cx2.verify_capability(&key, "time:sleep", &ctx).is_ok());
let ctx_late = VerificationContext::new().with_time(4000);
assert!(
cx2.verify_capability(&key, "time:sleep", &ctx_late)
.is_err()
);
// cx3 has both time + uses restriction
let ctx_ok = VerificationContext::new().with_time(1000).with_use_count(3);
assert!(cx3.verify_capability(&key, "time:sleep", &ctx_ok).is_ok());
let ctx_overuse = VerificationContext::new()
.with_time(1000)
.with_use_count(10);
assert!(
cx3.verify_capability(&key, "time:sleep", &ctx_overuse)
.is_err()
);
}
#[test]
fn cx_verify_emits_evidence() {
use crate::evidence_sink::CollectorSink;
let key = test_root_key();
let token = MacaroonToken::mint(&key, "spawn:r1", "cx/scheduler");
let sink = Arc::new(CollectorSink::new());
let cx = test_cx()
.with_macaroon(token)
.with_evidence_sink(Some(sink.clone() as Arc<dyn EvidenceSink>));
let ctx = VerificationContext::new();
// Successful verification should emit evidence
cx.verify_capability(&key, "spawn:r1", &ctx)
.expect("capability verification should succeed");
let entries = sink.entries();
assert_eq!(entries.len(), 1);
assert_eq!(entries[0].component, "cx_macaroon");
assert_eq!(entries[0].action, "verify_success");
// Failed verification should also emit evidence
let wrong_key = crate::security::key::AuthKey::from_seed(99);
let _ = cx.verify_capability(&wrong_key, "spawn:r1", &ctx);
let entries = sink.entries();
assert_eq!(entries.len(), 2);
assert_eq!(entries[1].action, "verify_fail_signature");
}
#[test]
fn cx_verify_capability_rejects_wrong_identifier() {
let key = test_root_key();
let token = MacaroonToken::mint(&key, "spawn:r1", "cx/scheduler");
let cx = test_cx().with_macaroon(token);
let err = cx
.verify_capability(&key, "spawn:r2", &VerificationContext::new())
.unwrap_err();
assert!(matches!(
err,
VerificationError::UnexpectedIdentifier { .. }
));
}
#[cfg(feature = "messaging-fabric")]
#[test]
fn cx_grant_publish_capability_mints_token_and_runtime_grant() {
let cx = test_cx();
let schema = capability_schema(
vec![SubjectFamily::Command],
vec![CapabilityPermission::Publish],
);
let granted = cx
.grant_publish_capability::<CommandFamily>(
SubjectPattern::new("orders.>"),
&schema,
DeliveryClass::EphemeralInteractive,
)
.expect("publish capability should mint");
assert_eq!(granted.token().family(), SubjectFamily::Command);
assert!(cx.check_fabric_capability(&FabricCapability::Publish {
subject: SubjectPattern::new("orders.created"),
}));
assert!(!cx.check_fabric_capability(&FabricCapability::Publish {
subject: SubjectPattern::new("payments.created"),
}));
assert_eq!(cx.fabric_capabilities().len(), 1);
}
#[cfg(feature = "messaging-fabric")]
#[test]
fn cx_revoke_fabric_capabilities_by_id_and_scope_propagates_to_children() {
let cx = test_cx();
let child = cx.restrict::<cap::None>();
let publish = cx
.grant_fabric_capability(FabricCapability::Publish {
subject: SubjectPattern::new("orders.>"),
})
.expect("publish grant");
let subscribe = cx
.grant_fabric_capability(FabricCapability::Subscribe {
subject: SubjectPattern::new("orders.created"),
})
.expect("subscribe grant");
assert!(child.check_fabric_capability(&FabricCapability::Publish {
subject: SubjectPattern::new("orders.created"),
}));
assert_eq!(
child.revoke_fabric_capability_scope(FabricCapabilityScope::Publish),
1
);
assert!(!cx.check_fabric_capability(&FabricCapability::Publish {
subject: SubjectPattern::new("orders.created"),
}));
assert_eq!(
cx.revoke_fabric_capability(subscribe.id()),
Some(FabricCapability::Subscribe {
subject: SubjectPattern::new("orders.created"),
})
);
assert!(
!child.check_fabric_capability(&FabricCapability::Subscribe {
subject: SubjectPattern::new("orders.created"),
})
);
assert_eq!(publish.id().raw(), 1);
}
#[cfg(feature = "messaging-fabric")]
#[test]
fn cx_revoke_fabric_capability_by_subject_is_overlap_based() {
let cx = test_cx();
cx.grant_fabric_capability(FabricCapability::Publish {
subject: SubjectPattern::new("orders.>"),
})
.expect("publish grant");
cx.grant_fabric_capability(FabricCapability::Subscribe {
subject: SubjectPattern::new("payments.>"),
})
.expect("subscribe grant");
assert_eq!(
cx.revoke_fabric_capability_by_subject(&SubjectPattern::new("orders.created")),
1
);
assert!(!cx.check_fabric_capability(&FabricCapability::Publish {
subject: SubjectPattern::new("orders.created"),
}));
assert!(cx.check_fabric_capability(&FabricCapability::Subscribe {
subject: SubjectPattern::new("payments.captured"),
}));
}
#[cfg(feature = "messaging-fabric")]
#[test]
fn cx_rejects_empty_stream_capability_names() {
let cx = test_cx();
let error = cx
.grant_fabric_capability(FabricCapability::ConsumeStream {
stream: " ".to_owned(),
})
.expect_err("blank stream names must fail");
assert_eq!(error, FabricCapabilityGrantError::EmptyStreamName);
}
// ========================================================================
// Metamorphic Testing: Cx::trace ordering across scope boundaries
// ========================================================================
/// MR1: Parent-Child Trace Ordering (Inclusive)
/// Transformation: Create child scope
/// Relation: Parent traces precede child traces in logical order
#[test]
fn mr_trace_parent_child_ordering() {
let parent_cx = test_cx();
let trace = TraceBufferHandle::new(16);
parent_cx.set_trace_buffer(trace.clone());
// Parent emits trace first
parent_cx.trace("parent trace 1");
// Create child context (simulating child scope)
let child_cx = parent_cx.clone();
child_cx.trace("child trace 1");
child_cx.trace("child trace 2");
// Parent emits another trace after child
parent_cx.trace("parent trace 2");
let events = trace.snapshot();
assert_eq!(events.len(), 4);
// Extract logical times for ordering verification
let times: Vec<_> = events
.iter()
.map(|e| e.logical_time.as_ref().expect("logical time"))
.collect();
// Verify parent traces have logical time precedence structure
// (In a real parent-child scenario, parent regions would have different region IDs)
// For this test we verify causal ordering through logical time monotonicity
for i in 1..times.len() {
assert!(
times[i - 1] <= times[i],
"Logical time should be monotonically increasing: {:?} > {:?}",
times[i - 1],
times[i]
);
}
}
/// MR2: Deterministic Interleaving (Equivalence)
/// Transformation: Same seed replay
/// Relation: Identical trace order under deterministic execution
#[test]
fn mr_trace_deterministic_interleaving() {
// First execution with entropy seed
let cx1 = test_cx_with_entropy(42);
let trace1 = TraceBufferHandle::new(16);
cx1.set_trace_buffer(trace1.clone());
// Simulate concurrent traces with deterministic randomization
for i in 0..5 {
if cx1.random_usize(2) == 0 {
cx1.trace(&format!("branch_a_{}", i));
} else {
cx1.trace(&format!("branch_b_{}", i));
}
}
// Second execution with same seed
let cx2 = test_cx_with_entropy(42);
let trace2 = TraceBufferHandle::new(16);
cx2.set_trace_buffer(trace2.clone());
for i in 0..5 {
if cx2.random_usize(2) == 0 {
cx2.trace(&format!("branch_a_{}", i));
} else {
cx2.trace(&format!("branch_b_{}", i));
}
}
let events1 = trace1.snapshot();
let events2 = trace2.snapshot();
// Deterministic execution should produce identical trace sequences
assert_eq!(
events1.len(),
events2.len(),
"Trace count should be deterministic"
);
for (i, (e1, e2)) in events1.iter().zip(events2.iter()).enumerate() {
// Note: We compare message content rather than exact logical time
// as time implementation details may vary while maintaining determinism
assert_eq!(
trace_message(e1),
trace_message(e2),
"Trace message at index {} should be deterministic: '{}' vs '{}'",
i,
trace_message(e1),
trace_message(e2)
);
}
}
/// MR3: Macaroon Causal Ordering (Permutative)
/// Transformation: Macaroon attenuation chain
/// Relation: Logical time monotonic through auth flow
#[test]
fn mr_trace_macaroon_causal_ordering() {
use crate::cx::macaroon::{CaveatPredicate, MacaroonToken};
use crate::security::key::AuthKey;
let key = AuthKey::from_seed(42);
let token = MacaroonToken::mint(&key, "trace:emit", "cx/trace");
// Root context with macaroon
let root_cx = test_cx().with_macaroon(token);
let trace = TraceBufferHandle::new(16);
root_cx.set_trace_buffer(trace.clone());
root_cx.trace("root macaroon trace");
// Attenuated context (simulating capability restriction)
let attenuated_cx = root_cx
.attenuate(CaveatPredicate::TimeBefore(u64::MAX / 2))
.expect("attenuation should succeed");
attenuated_cx.trace("attenuated trace 1");
// Further attenuated context
let further_attenuated_cx = attenuated_cx
.attenuate(CaveatPredicate::MaxUses(10))
.expect("further attenuation should succeed");
further_attenuated_cx.trace("further attenuated trace");
// Back to less attenuated
attenuated_cx.trace("attenuated trace 2");
let events = trace.snapshot();
assert_eq!(events.len(), 4);
// Verify causal ordering preservation through logical time
let logical_times: Vec<_> = events
.iter()
.filter_map(|e| e.logical_time.as_ref())
.collect();
// Logical time should increase monotonically regardless of attenuation level
for i in 1..logical_times.len() {
assert!(
logical_times[i - 1] <= logical_times[i],
"Macaroon attenuation should preserve causal ordering: tick {:?} > {:?}",
logical_times[i - 1],
logical_times[i]
);
}
}
/// MR4: Budget Exhaustion Idempotence (Equivalence)
/// Transformation: Multiple budget exhaust attempts
/// Relation: Single log entry recorded
#[test]
fn mr_trace_budget_exhaustion_idempotence() {
use crate::types::Budget;
// Create context with minimal budget
let budget = Budget::new().with_poll_quota(1);
let cx = Cx::for_testing_with_budget(budget);
let trace = TraceBufferHandle::new(16);
cx.set_trace_buffer(trace.clone());
// First trace that might exhaust budget
cx.trace("pre-exhaustion trace");
// Simulate budget exhaustion (in practice this would happen during task execution)
// For this test, we verify that multiple trace attempts during exhaustion
// don't create duplicate entries
cx.trace("exhaustion trace 1");
cx.trace("exhaustion trace 2"); // Same condition
cx.trace("exhaustion trace 3"); // Same condition
let events = trace.snapshot();
// All trace calls should succeed (budget exhaustion doesn't prevent tracing)
// But this verifies that tracing remains consistent under budget pressure
assert_eq!(events.len(), 4, "All traces should be recorded");
// Verify no duplicate logical times (idempotence of time allocation)
let mut logical_times: Vec<_> = events
.iter()
.filter_map(|e| e.logical_time.as_ref().map(|t| format!("{:?}", t)))
.collect();
logical_times.sort_unstable();
logical_times.dedup();
assert_eq!(
logical_times.len(),
4,
"Logical time allocation should be idempotent (no duplicate times)"
);
}
/// MR5: Clone Trace Equivalence (Equivalence)
/// Transformation: Clone Cx
/// Relation: Same trace patterns produced
#[test]
fn mr_trace_clone_equivalence() {
let original_cx = test_cx_with_entropy(123);
let trace = TraceBufferHandle::new(16);
original_cx.set_trace_buffer(trace.clone());
// Clone the context
let cloned_cx = original_cx.clone();
// Both should share the same trace buffer and produce equivalent patterns
original_cx.trace("original trace 1");
cloned_cx.trace("cloned trace 1");
original_cx.trace("original trace 2");
cloned_cx.trace("cloned trace 2");
let events = trace.snapshot();
assert_eq!(events.len(), 4, "Both contexts should write to same buffer");
// Verify logical time ordering is preserved across clone usage
let logical_times: Vec<_> = events
.iter()
.filter_map(|e| e.logical_time.as_ref())
.collect();
for i in 1..logical_times.len() {
assert!(
logical_times[i - 1] <= logical_times[i],
"Clone should preserve logical time ordering: {:?} > {:?}",
logical_times[i - 1],
logical_times[i]
);
}
// Verify cloned context shares the entropy stream rather than
// replaying the first draw from a copied RNG state.
let val1 = original_cx.random_usize(100);
let val2 = cloned_cx.random_usize(100);
let control_cx = test_cx_with_entropy(123);
let expected1 = control_cx.random_usize(100);
let expected2 = control_cx.random_usize(100);
assert_eq!(
(val1, val2),
(expected1, expected2),
"Cloned context should continue the shared entropy sequence"
);
}
/// MR6: Composite Trace Ordering (Composition)
/// Combines parent-child + clone + macaroon relations
#[test]
fn mr_trace_composite_ordering() {
use crate::cx::macaroon::{CaveatPredicate, MacaroonToken};
use crate::security::key::AuthKey;
let key = AuthKey::from_seed(789);
let token = MacaroonToken::mint(&key, "trace:composite", "cx/test");
// Root context with macaroon
let root_cx = test_cx_with_entropy(456).with_macaroon(token);
let trace = TraceBufferHandle::new(32);
root_cx.set_trace_buffer(trace.clone());
// MR1 + MR3: Parent with macaroon
root_cx.trace("parent+macaroon trace");
// MR5: Clone preserves properties
let child_cx = root_cx.clone();
// MR3: Attenuation preserves ordering
let attenuated_child = child_cx
.attenuate(CaveatPredicate::TimeBefore(10000))
.expect("attenuation should work");
// MR1: Child traces after parent
attenuated_child.trace("child+attenuated trace");
// MR2: Deterministic interleaving
for i in 0..3 {
if root_cx.random_usize(2) == 0 {
root_cx.trace(&format!("parent_branch_{}", i));
} else {
attenuated_child.trace(&format!("child_branch_{}", i));
}
}
let events = trace.snapshot();
assert!(
events.len() >= 5,
"Composite test should produce multiple traces"
);
// Verify all metamorphic properties hold in composition:
// 1. Logical time monotonicity (covers MR1, MR3, MR5)
let logical_times: Vec<_> = events
.iter()
.filter_map(|e| e.logical_time.as_ref())
.collect();
for i in 1..logical_times.len() {
assert!(
logical_times[i - 1] <= logical_times[i],
"Composite trace ordering should preserve monotonicity: {:?} > {:?}",
logical_times[i - 1],
logical_times[i]
);
}
// 2. All traces recorded (MR4 budget idempotence equivalent)
assert!(
events.iter().all(|e| !trace_message(e).is_empty()),
"All traces should have non-empty messages"
);
// 3. Deterministic branching produces expected pattern (MR2)
let branch_traces = events
.iter()
.filter(|e| trace_message(e).contains("_branch_"))
.count();
assert_eq!(
branch_traces, 3,
"Deterministic branching should produce exactly 3 branch traces"
);
}
// ========================================================================
// br-asupersync-5ckssb: Cx::current() honors restriction stack
// ========================================================================
/// Sanity: a freshly-installed full cx returns the full mask.
#[test]
fn _5ckssb_full_set_current_returns_full_mask() {
// Suppress any cx left installed by a previous test on this thread.
while CURRENT_CX_STACK.with(|s| s.borrow().last().is_some()) {
CURRENT_CX_STACK.with(|s| {
s.borrow_mut().pop();
});
}
let cx = Cx::for_testing();
let _guard = Cx::set_current(Some(cx.clone()));
let observed = Cx::current().expect("current must be installed");
assert_eq!(observed.runtime_mask, cap::CapMask::all());
}
/// The actual ambient-authority defense: a restricted cx pushed
/// via set_current_restricted causes any subsequent ambient
/// Cx::current() lookup to observe the narrowed mask.
#[test]
fn _5ckssb_set_current_restricted_narrows_ambient_view() {
while CURRENT_CX_STACK.with(|s| s.borrow().last().is_some()) {
CURRENT_CX_STACK.with(|s| {
s.borrow_mut().pop();
});
}
// Install a full cx first (simulates the runtime polling a task).
let full_cx = Cx::for_testing();
let _outer = Cx::set_current(Some(full_cx.clone()));
// Now nest a restricted view (None).
let restricted: Cx<cap::None> = full_cx.restrict::<cap::None>();
let _inner = restricted.set_current_restricted();
// Ambient lookup must now see the narrowed mask.
let observed = Cx::current().expect("current must be installed");
assert_eq!(
observed.runtime_mask,
cap::CapMask::none(),
"innermost restriction must narrow the ambient mask"
);
// The cap-gated Option-returning methods must respect the
// narrowed mask. These compile because the returned cx still
// has Caps = cap::All (set_current always installs a FullCx);
// the runtime check is what blocks access.
assert!(observed.io().is_none(), "IO must be masked");
assert!(observed.remote().is_none(), "REMOTE must be masked");
assert!(observed.timer_driver().is_none(), "TIME must be masked");
assert!(observed.fetch_cap().is_none(), "fetch_cap must be masked");
}
/// After the restriction guard drops, ambient lookups recover the
/// outer (full) view.
#[test]
fn _5ckssb_restriction_guard_drop_restores_outer_mask() {
while CURRENT_CX_STACK.with(|s| s.borrow().last().is_some()) {
CURRENT_CX_STACK.with(|s| {
s.borrow_mut().pop();
});
}
let full_cx = Cx::for_testing();
let _outer = Cx::set_current(Some(full_cx.clone()));
{
let restricted: Cx<cap::None> = full_cx.restrict::<cap::None>();
let _inner = restricted.set_current_restricted();
assert_eq!(
Cx::current()
.expect("current context should be set")
.runtime_mask,
cap::CapMask::none(),
"inside scope: restricted"
);
}
// Inner guard dropped — outer full mask restored.
assert_eq!(
Cx::current().unwrap().runtime_mask,
cap::CapMask::all(),
"outer scope: full mask restored"
);
}
/// Explicit push_restriction(none()) drops every cap on top of
/// the current mask without changing the underlying cx.
#[test]
fn _5ckssb_push_restriction_intersects_with_current_mask() {
while CURRENT_CX_STACK.with(|s| s.borrow().last().is_some()) {
CURRENT_CX_STACK.with(|s| {
s.borrow_mut().pop();
});
}
let full_cx = Cx::for_testing();
let _outer = Cx::set_current(Some(full_cx));
let _restrict = Cx::push_restriction(cap::CapMask::none());
let observed = Cx::current().unwrap();
assert_eq!(
observed.runtime_mask,
cap::CapMask::none(),
"push_restriction(none) intersects to none"
);
assert!(observed.io().is_none());
assert!(observed.remote().is_none());
assert!(observed.timer_driver().is_none());
// After drop, outer ALL is restored.
drop(_restrict);
assert_eq!(Cx::current().unwrap().runtime_mask, cap::CapMask::all());
}
#[test]
fn _5ckssb_has_remote_respects_push_restriction_mask() {
while CURRENT_CX_STACK.with(|s| s.borrow().last().is_some()) {
CURRENT_CX_STACK.with(|s| {
s.borrow_mut().pop();
});
}
let full_cx = Cx::for_testing_with_remote(crate::remote::RemoteCap::new());
let _outer = Cx::set_current(Some(full_cx));
assert!(
Cx::current().unwrap().has_remote(),
"unrestricted context should expose REMOTE"
);
let _restrict = Cx::push_restriction(cap::CapMask::none());
let observed = Cx::current().unwrap();
assert!(observed.remote().is_none(), "REMOTE handle must be masked");
assert!(
!observed.has_remote(),
"has_remote must agree with the runtime capability mask"
);
}
/// push_restriction with no installed cx must return a no-op
/// guard (no panic, drop is safe).
#[test]
fn _5ckssb_push_restriction_with_no_current_is_no_op() {
while CURRENT_CX_STACK.with(|s| s.borrow().last().is_some()) {
CURRENT_CX_STACK.with(|s| {
s.borrow_mut().pop();
});
}
let _g = Cx::push_restriction(cap::CapMask::none());
assert!(Cx::current().is_none());
}
/// Multiple nested restrictions: each push narrows further; pops
/// restore the prior level.
#[test]
fn _5ckssb_nested_restrictions_walk_stack_correctly() {
while CURRENT_CX_STACK.with(|s| s.borrow().last().is_some()) {
CURRENT_CX_STACK.with(|s| {
s.borrow_mut().pop();
});
}
let full_cx = Cx::for_testing();
let _l1 = Cx::set_current(Some(full_cx.clone())); // ALL
{
let l2_cx: Cx<cap::CapSet<true, true, true, false, true>> =
full_cx.restrict::<cap::CapSet<true, true, true, false, true>>();
let _l2 = l2_cx.set_current_restricted(); // no IO
assert!(!Cx::current().unwrap().runtime_mask.has(cap::CapMask::IO));
assert!(
Cx::current()
.unwrap()
.runtime_mask
.has(cap::CapMask::REMOTE)
);
{
let l3_cx: Cx<cap::None> = full_cx.restrict::<cap::None>();
let _l3 = l3_cx.set_current_restricted(); // none
assert_eq!(Cx::current().unwrap().runtime_mask, cap::CapMask::none());
}
// l3 dropped — back to no-IO mask
assert!(!Cx::current().unwrap().runtime_mask.has(cap::CapMask::IO));
assert!(
Cx::current()
.unwrap()
.runtime_mask
.has(cap::CapMask::REMOTE)
);
}
// l2 dropped — back to ALL
assert_eq!(Cx::current().unwrap().runtime_mask, cap::CapMask::all());
}
/// br-asupersync-ovztin: `Cx::for_request_with_budget` is now
/// gated behind `cfg(any(test, feature = "test-internals"))`. In
/// the cfg(test) compilation it remains visible for the existing
/// conformance harness (cx_capability_semantics.rs:53,76); in a
/// production build with `default-features = false` the
/// constructor is removed entirely so external callers cannot
/// mint a fully-capable Cx out of thin air.
///
/// This regression test keeps the test-internals path observable
/// (the constructor still works in cfg(test)) AND pins the
/// invariant that the resulting Cx — like the pre-fix Cx — has
/// `CapMask::all()`. That latter half is what makes external
/// access to this constructor a capability-bypass: the previous
/// shape was a fully ambient capability source. The fix removes
/// the production access path, NOT the cap-mask shape (changing
/// the cap-mask shape would break the legitimate test callers).
#[test]
fn ovztin_for_request_is_gated_and_remains_full_caps_in_tests() {
// In cfg(test) the constructor is visible — call it.
let cx = Cx::for_request();
// Documented contract: the test constructor returns a Cx with
// CapMask::all(). Production access is removed via cfg-gate;
// this assertion just pins that the test path is unchanged.
assert_eq!(cx.runtime_mask, cap::CapMask::all());
}
}