freenet 0.2.75

Freenet core software
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
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
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
//! Task-per-transaction GET drivers.
//!
//! Each entry point — client-initiated, relay, sub-op, targeted
//! sub-op — owns routing state in task locals. No `GetOp` is pushed
//! into `OpManager.ops.get`.
//!
//! # Client-initiated flow
//!
//! 1. Loop calling [`OpCtx::send_and_await`] with a fresh
//!    `Transaction` per attempt (single-use-per-tx constraint).
//! 2. Terminal `Response{Found}`: store the returned state into the
//!    local executor via `PutQuery`, run hosting / access-tracking /
//!    announce side effects, publish
//!    `HostResponse::ContractResponse::GetResponse`. The reply
//!    bypass intercepts before `process_message` would run on the
//!    originator, so the driver is the only place these side effects
//!    happen.
//! 3. Terminal `ResponseStreaming`: deliver the final payload via a
//!    store re-query using the contract key from the envelope.
//! 4. Terminal Request-echo: the pre-send local-cache shortcut in
//!    `client_events.rs` already returned the state; the driver
//!    resolves the `ContractKey` for telemetry and client delivery.
//! 5. `Response{NotFound}`: advance to next peer.
//! 6. Timeout / wire-error: advance or exhaust.
//!
//! # Connection-drop latency
//!
//! Disconnect detection is event-driven: when a peer disconnects,
//! `Ring::prune_connection` enumerates `LiveTransactionTracker` orphans
//! and `P2pBridge::handle_orphaned_transactions` emits
//! `NodeEvent::TransactionCompleted` for each, which closes the
//! parked driver's `pending_op_results` waiter. Wake latency is
//! sub-millisecond (#4154). `OPERATION_TTL` (60 s) remains the upper
//! bound for cases where the downstream peer never formally
//! disconnects — silent stalls, slow-loris, partition-without-prune.

use std::net::SocketAddr;
use std::sync::Arc;

use freenet_stdlib::client_api::{ContractResponse, ErrorKind, HostResponse};
use freenet_stdlib::prelude::*;

use crate::client_events::HostResult;
use crate::config::{GlobalExecutor, OPERATION_TTL};
use crate::contract::{ContractHandlerEvent, StoreResponse};
use crate::message::{NetMessage, NetMessageV1, NodeEvent, Transaction};
use crate::node::NetworkBridge;
use crate::node::OpManager;
#[rustfmt::skip]
use crate::operations::op_ctx::{
    AdvanceOutcome, AttemptOutcome, RetryDriver, RetryLoopOutcome, drive_retry_loop,
};
use crate::operations::OpError;
use crate::operations::VisitedPeers;
use crate::ring::{Location, PeerKeyLocation};
use crate::router::{RouteEvent, RouteOutcome};
use crate::transport::peer_connection::StreamId;

use super::{GetMsg, GetMsgResult, GetStreamingPayload};
use crate::operations::orphan_streams::{OrphanStreamError, STREAM_CLAIM_TIMEOUT};

/// Test-only counter that increments every time `start_client_get` is
/// called. Used by integration tests to verify that a GET actually
/// routed through the driver rather than being satisfied
/// by the `client_events.rs` local-cache shortcut.
#[cfg(any(test, feature = "testing"))]
pub static DRIVER_CALL_COUNT: std::sync::atomic::AtomicUsize =
    std::sync::atomic::AtomicUsize::new(0);

/// Test-only counter that increments every time `start_relay_get` is
/// called. Used by integration tests to verify that relay dispatch
/// actually routed a fresh inbound Request through the driver
/// driver (and not through the legacy `handle_op_request` path that
/// continues to serve originator loop-back, GC-spawned retries, and
/// `start_targeted_op` UPDATE-triggered auto-fetches).
#[cfg(any(test, feature = "testing"))]
pub static RELAY_DRIVER_CALL_COUNT: std::sync::atomic::AtomicUsize =
    std::sync::atomic::AtomicUsize::new(0);

/// Number of relay-GET driver tasks currently executing. Incremented
/// on spawn, decremented on completion (both success and error paths).
/// Surfaced via the periodic `memory_stats` dump so we can correlate
/// RSS growth with spawn/complete rate and rule in/out a spawn storm
/// vs. per-task memory bloat as the cause of phase-5 OOMs.
pub static RELAY_INFLIGHT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);

/// Lifetime count of relay-GET driver spawns. Paired with
/// `RELAY_COMPLETED_TOTAL` so the `memory_stats` dump can show whether
/// spawn rate exceeds completion rate (drivers stuck in retry loops)
/// vs. balanced (per-task bloat is the culprit).
pub static RELAY_SPAWNED_TOTAL: std::sync::atomic::AtomicUsize =
    std::sync::atomic::AtomicUsize::new(0);

/// Lifetime count of relay-GET driver completions. See
/// `RELAY_SPAWNED_TOTAL`.
pub static RELAY_COMPLETED_TOTAL: std::sync::atomic::AtomicUsize =
    std::sync::atomic::AtomicUsize::new(0);

/// Lifetime count of relay-GET spawns rejected by the dedup gate
/// because a driver for the same `incoming_tx` was already active on
/// this node. Surfaced via `memory_stats` so we can confirm the gate
/// fires under fault-loss retry retransmissions.
pub static RELAY_DEDUP_REJECTS: std::sync::atomic::AtomicUsize =
    std::sync::atomic::AtomicUsize::new(0);

/// Test-only counter that increments every time the relay GET driver
/// commits to forking + piping a streaming response to a REMOTE upstream
/// (the `Terminal::Streaming` forward branch). Incremented after the
/// loopback safety-net check and a successful `claim_or_wait`, before the
/// header send. NOT incremented on the loopback branch or the
/// `AlreadyClaimed` dedup branch. Used by `streaming_e2e` to prove a GET
/// genuinely relayed through a streaming hop rather than falling back to
/// store-and-forward. Mirrors `RELAY_PUT_STREAMING_DRIVER_CALL_COUNT`.
#[cfg(any(test, feature = "testing"))]
pub static RELAY_GET_STREAMING_FORWARD_COUNT: std::sync::atomic::AtomicUsize =
    std::sync::atomic::AtomicUsize::new(0);

/// Start a client-initiated GET, returning as soon as the task has been
/// spawned (mirrors legacy `request_get` timing).
///
/// The caller must have already registered a result waiter for
/// `client_tx` via `op_manager.ch_outbound.waiting_for_transaction_result`.
/// This function does NOT touch the waiter; it only drives the
/// ring/network side and publishes the terminal result to
/// `result_router_tx` keyed by `client_tx`.
#[allow(clippy::too_many_arguments)]
pub(crate) async fn start_client_get(
    op_manager: Arc<OpManager>,
    client_tx: Transaction,
    instance_id: ContractInstanceId,
    return_contract_code: bool,
    subscribe: bool,
    blocking_subscribe: bool,
) -> Result<Transaction, OpError> {
    // Phase 7 egress self-block (#4300): refuse to originate a GET for
    // a contract this node has banned, BEFORE spawning the driver.
    // Mirrors the receive-side `GetMsg::Request` drop in node.rs (PR
    // #4299). The client gets a typed `ContractBanned` error.
    crate::operations::reject_if_contract_banned(&op_manager, &instance_id)?;

    // Test-only: count driver invocations so integration tests can
    // assert the driver was actually called (as opposed to
    // `client_events.rs`'s local-cache shortcut satisfying the GET).
    // Removed under #[cfg(not(any(test, feature = "testing")))].
    #[cfg(any(test, feature = "testing"))]
    DRIVER_CALL_COUNT.fetch_add(1, std::sync::atomic::Ordering::SeqCst);

    tracing::debug!(
        tx = %client_tx,
        contract = %instance_id,
        "get: spawning client-initiated task"
    );

    // Fire-and-forget spawn; same rationale as PUT 3a's `start_client_put`.
    // Failures are published to the client via `result_router_tx`, not
    // via this function's return value. Not registered with
    // `BackgroundTaskMonitor`: per-transaction task that terminates via
    // happy path, exhaustion, timeout, or infra error.
    //
    // Atomic admission gate + counter bump (closes the drain race
    // window). See `OpManager::admit_client_op` for the race
    // analysis. The guard is held for the lifetime of the spawned
    // driver; see `ClientOpGuard` rustdoc for the broader
    // shutdown-drain contract.
    let inflight_guard = match op_manager.admit_client_op() {
        Some(g) => g,
        None => return Err(OpError::NodeShuttingDown),
    };
    GlobalExecutor::spawn(async move {
        let _inflight_guard = inflight_guard;
        run_client_get(
            op_manager,
            client_tx,
            instance_id,
            return_contract_code,
            subscribe,
            blocking_subscribe,
        )
        .await;
    });

    Ok(client_tx)
}

async fn run_client_get(
    op_manager: Arc<OpManager>,
    client_tx: Transaction,
    instance_id: ContractInstanceId,
    return_contract_code: bool,
    subscribe: bool,
    blocking_subscribe: bool,
) {
    // RAII guard: clears the ops.get entry that the originator
    // loopback pushes via legacy process_message::GetMsg::Request
    // (#4066; full rationale in .claude/rules/operations.md).
    let _completion_guard = ClientGetCompletionGuard {
        op_manager: op_manager.clone(),
        client_tx,
    };

    let outcome = drive_client_get(
        op_manager.clone(),
        client_tx,
        instance_id,
        return_contract_code,
        subscribe,
        blocking_subscribe,
    )
    .await;
    deliver_outcome(&op_manager, client_tx, outcome);
}

/// RAII guard that calls `op_manager.completed(client_tx)` on drop,
/// covering every exit path including panics. Documented at the
/// guard installation site in `run_client_get`.
struct ClientGetCompletionGuard {
    op_manager: Arc<OpManager>,
    client_tx: Transaction,
}

impl Drop for ClientGetCompletionGuard {
    fn drop(&mut self) {
        self.op_manager.completed(self.client_tx);
    }
}

/// GET driver has exactly two outcomes, matching PUT 3a.
#[derive(Debug)]
enum DriverOutcome {
    /// The driver produced a `HostResult` that must be published via
    /// `result_router_tx`.
    Publish(HostResult),
    /// A genuine infrastructure failure escaped the driver loop.
    InfrastructureError(OpError),
}

async fn drive_client_get(
    op_manager: Arc<OpManager>,
    client_tx: Transaction,
    instance_id: ContractInstanceId,
    return_contract_code: bool,
    subscribe: bool,
    blocking_subscribe: bool,
) -> DriverOutcome {
    match drive_client_get_inner(
        &op_manager,
        client_tx,
        instance_id,
        return_contract_code,
        subscribe,
        blocking_subscribe,
    )
    .await
    {
        Ok(outcome) => outcome,
        Err(err) => DriverOutcome::InfrastructureError(err),
    }
}

async fn drive_client_get_inner(
    op_manager: &Arc<OpManager>,
    client_tx: Transaction,
    instance_id: ContractInstanceId,
    return_contract_code: bool,
    subscribe: bool,
    blocking_subscribe: bool,
) -> Result<DriverOutcome, OpError> {
    let htl = op_manager.ring.max_hops_to_live;

    // Pre-select initial target for the driver's retry state. Actual
    // routing is done by `process_message` on the loop-back; this is
    // just so `advance_to_next_peer` has a starting "tried" set.
    //
    // At the client-API boundary we only have an instance_id — the
    // full ContractKey (which includes the code hash) isn't known
    // until a terminal reply with `GetMsgResult::Found` arrives.
    // `k_closest_potentially_hosting` accepts either.
    let mut tried: Vec<std::net::SocketAddr> = Vec::new();
    if let Some(own_addr) = op_manager.ring.connection_manager.get_own_addr() {
        tried.push(own_addr);
    }
    let initial_target = op_manager
        .ring
        .k_closest_potentially_hosting(&instance_id, tried.as_slice(), 1)
        .into_iter()
        .next();
    let current_target = match initial_target {
        Some(peer) => {
            if let Some(addr) = peer.socket_addr() {
                tried.push(addr);
            }
            peer
        }
        // Bootstrap fallback (#4361): with an empty ring, attribute the
        // attempt to a configured gateway — the loopback relay's own
        // fallback forwards there, so the gateway IS the real first hop.
        // `own_location()` (below) remains only for the genuinely
        // isolated case (no ring, no gateways).
        None => match bootstrap_gateway_target(op_manager, |addr| tried.contains(&addr)) {
            Some((gw, addr)) => {
                tracing::info!(
                    %instance_id,
                    gateway = %addr,
                    "GET client: ring empty — initial target falls back to configured gateway"
                );
                tried.push(addr);
                gw
            }
            None => op_manager.ring.connection_manager.own_location(),
        },
    };

    let mut driver = GetRetryDriver {
        op_manager,
        instance_id,
        htl,
        tried,
        retries: 0,
        current_target,
        attempt_visited: VisitedPeers::new(&client_tx),
        request_sent_at: None,
        response_received_at: None,
    };

    let (loop_result, streaming_assembly) = drive_get_with_assembly_retry(
        op_manager,
        client_tx,
        "get",
        &mut driver,
        /* emit_route_failure_on_retry */ true,
    )
    .await;

    // `op_manager.completed(client_tx)` runs from the
    // `ClientGetCompletionGuard` in `run_client_get` AFTER this fn
    // returns (and the side-effect block below has run). Do not add
    // explicit `completed()` calls in the arms here — doing so would
    // race the originator-side side effects (`cache_contract_locally`,
    // `auto_subscribe_on_get_response`, `maybe_subscribe_child`)
    // because once the tx is in `ops.completed`, any
    // `op_manager.push(...)` for that tx is silently dropped (see
    // `op_state_manager.rs::push` short-circuit on
    // `ops.completed.contains`).

    match loop_result {
        RetryLoopOutcome::Done(terminal) => {
            // Mirror the originator-side side effects that the legacy
            // `process_message` Response{Found} branch does
            // (`get.rs:2218–2450`): PutQuery the fetched state into
            // the local executor so re-GETs / local-cache checks / the
            // hosting LRU see it, announce hosting, and record the
            // access. Without this, a client-initiated GET succeeds
            // on the wire but the requesting node never stores the
            // contract — which broke `test_get_routing_coverage_low_htl`
            // and `test_auto_fetch_from_update_sender` on CI when the
            // bypass was first introduced.
            //
            // The bypass at `node.rs::handle_pure_network_message_v1`
            // intercepts the terminal reply BEFORE `process_message`
            // runs on the originator, so the driver is the only
            // place these side effects can happen.
            // Payload accounting for the router's `transfer_rate_estimator`
            // (router.rs:443) and `response_start_time_estimator`
            // (router.rs:405). Set on the InlineFound/Streaming success
            // paths; `Terminal::LocalCompletion` is the loopback
            // Request-echo with no network round-trip — both stay zero
            // AND we explicitly null the captured per-attempt timing
            // below (see `timed_outcome`) to avoid poisoning the
            // response-time model with sub-millisecond loopback latency
            // samples attributed to `driver.current_target`.
            let mut payload_size: usize = 0;
            let mut transfer_duration: std::time::Duration = std::time::Duration::ZERO;

            let reply_key = match &terminal {
                Terminal::InlineFound {
                    key,
                    state,
                    contract,
                    hop_count: _,
                } => {
                    // InlineFound delivers state + optional contract in
                    // the same envelope as the Response header, so the
                    // payload transfer time is effectively zero — the
                    // bytes arrived alongside the response. The router
                    // deliberately skips `transfer_rate_estimator`
                    // observations with `transfer_time.is_zero()`
                    // (router.rs:443) so InlineFound feeds response-time
                    // only; the legacy `GetStats` shape did the same
                    // thing for the same reason (no measurable transfer
                    // phase for an envelope-bundled payload).
                    payload_size =
                        state.size() + contract.as_ref().map(|c| c.data().len()).unwrap_or(0);
                    cache_contract_locally(
                        op_manager,
                        *key,
                        state.clone(),
                        contract.clone(),
                        true, // client driver: this node initiated the GET
                    )
                    .await;
                    *key
                }
                Terminal::Streaming {
                    key, total_size, ..
                } => {
                    // `total_size` is the wire-authoritative payload byte
                    // count from the `ResponseStreaming` header. Using it
                    // here (rather than re-querying the local store after
                    // `cache_contract_locally`) prevents a TOCTOU race
                    // where a concurrent UPDATE for the same contract
                    // would mis-attribute a different payload's size to
                    // this GET's transfer-rate observation, and side-steps
                    // a separate "store evicted before re-query"
                    // failure mode (the LRU has finite capacity).
                    payload_size = *total_size as usize;
                    // Stream assembly (with per-candidate retry, #4345)
                    // already ran inside `drive_get_with_assembly_retry`
                    // — consume its timing here. `None` means every
                    // assembly attempt failed: leave `transfer_duration`
                    // at ZERO so the router skips the rate sample at
                    // router.rs:443 (the response-time observation still
                    // goes through because a header DID arrive).
                    if let Some(duration) = streaming_assembly.transfer_duration {
                        transfer_duration = duration;
                    }
                    *key
                }
                Terminal::LocalCompletion => {
                    // Request-echo: the pre-send local-cache shortcut
                    // in `client_events.rs` already returned a cached
                    // state directly, so reaching here means
                    // `request_get`'s fallback cached it. The store
                    // already has the bytes; just resolve the key.
                    match lookup_stored_key(op_manager, &instance_id).await {
                        Some(k) => k,
                        None => synthetic_key(&instance_id),
                    }
                }
            };

            let host_result = build_host_response(
                op_manager,
                &instance_id,
                return_contract_code,
                streaming_assembly.error.as_deref(),
            )
            .await;

            // Auto-subscribe on successful GET at the originator —
            // mirrors the legacy branches at get.rs:2313/2408/3136/3185.
            // AUTO_SUBSCRIBE_ON_GET (ring.rs:60) is a const; we still
            // guard on `is_subscribed` to avoid duplicate registration
            // if the request-router already wired up a subscribe.
            //
            // When the client explicitly set `subscribe=true`, the
            // dedicated `maybe_subscribe_child` path below runs — skip
            // auto-subscribe here so we never double-subscribe.
            if host_result.is_ok()
                && !subscribe
                && crate::ring::AUTO_SUBSCRIBE_ON_GET
                && !op_manager.ring.is_subscribed(&reply_key)
            {
                let path_label = match &terminal {
                    Terminal::Streaming { .. } => "streaming",
                    Terminal::InlineFound { .. } | Terminal::LocalCompletion => "non-streaming",
                };
                crate::operations::auto_subscribe_on_get_response(
                    op_manager,
                    &reply_key,
                    &client_tx,
                    &Some(driver.current_target.clone()),
                    /* subscribe_requested */ false,
                    /* blocking_sub */ blocking_subscribe,
                    path_label,
                )
                .await;
            }

            // Emit routing event + telemetry — `report_result` (which
            // normally does both) doesn't run because the bypass
            // intercepted the Response. Without this, the router's
            // prediction model never receives GET success feedback.
            //
            // Prefer the timed `Success` variant so the router's
            // `response_start_time_estimator` and
            // `transfer_rate_estimator` receive observations. Fall back
            // to `SuccessUntimed` only when the reply was a loopback
            // Request-echo (`Terminal::LocalCompletion`) — there is no
            // wire round-trip to measure, so the captured per-attempt
            // timing reflects pure in-process latency and would poison
            // the response-time model with sub-millisecond samples
            // attributed to the selected target peer. The other paths
            // (InlineFound + Streaming) do measure real wire round-trip
            // time. Without timed Success on those paths the dashboard's
            // Response Time and Transfer Rate charts stay permanently
            // empty because those estimators are fed exclusively from
            // `RouteOutcome::Success`. The success flag tracks the
            // actual client-visible outcome (`host_result.is_ok()`), not
            // the wire-level reply — if the store re-query returned
            // nothing the client sees `OperationError` and telemetry
            // must agree.
            let contract_location = Location::from(&reply_key);
            let timed_outcome = if matches!(terminal, Terminal::LocalCompletion) {
                None
            } else {
                match (driver.request_sent_at, driver.response_received_at) {
                    (Some(sent), Some(received)) if received >= sent => {
                        Some(RouteOutcome::Success {
                            time_to_response_start: received.duration_since(sent),
                            payload_size,
                            payload_transfer_time: transfer_duration,
                        })
                    }
                    (Some(sent), Some(received)) => {
                        // `tokio::time::Instant` is monotonic, so this
                        // arm should be unreachable on real hardware.
                        // Logging instead of silently masking guards
                        // against a clock-source regression slipping in
                        // unnoticed.
                        tracing::warn!(
                            tx = %client_tx,
                            sent_at_elapsed_secs = sent.elapsed().as_secs_f64(),
                            received_at_elapsed_secs = received.elapsed().as_secs_f64(),
                            "get: received < sent on winning attempt; \
                             falling back to SuccessUntimed"
                        );
                        None
                    }
                    _ => None,
                }
            };
            let route_event = RouteEvent {
                peer: driver.current_target.clone(),
                contract_location,
                outcome: if host_result.is_ok() {
                    timed_outcome.unwrap_or(RouteOutcome::SuccessUntimed)
                } else {
                    RouteOutcome::Failure
                },
                op_type: Some(crate::node::network_status::OpType::Get),
            };
            if let Some(log_event) =
                crate::tracing::NetEventLog::route_event(&client_tx, &op_manager.ring, &route_event)
            {
                op_manager
                    .ring
                    .register_events(either::Either::Left(log_event))
                    .await;
            }
            op_manager.ring.routing_finished(route_event);
            crate::node::network_status::record_op_result(
                crate::node::network_status::OpType::Get,
                host_result.is_ok(),
            );

            // Explicit-subscribe hand-off. Mirrors PUT 3a's
            // `maybe_subscribe_child` — subscribe is never handled in
            // the terminal-result construction to avoid double-subscribe
            // (commit 494a3c69). This only runs when the client set
            // `subscribe=true`; the auto-subscribe path above handles
            // the AUTO_SUBSCRIBE_ON_GET fallback.
            maybe_subscribe_child(
                op_manager,
                client_tx,
                reply_key,
                subscribe,
                blocking_subscribe,
            )
            .await;

            Ok(DriverOutcome::Publish(host_result))
        }
        RetryLoopOutcome::Exhausted(cause) => {
            // Exhaustion after retry loop means every peer either responded
            // NotFound or the operation could not be forwarded at all
            // (e.g., isolated gateway with zero ring connections). Surface
            // as `ContractResponse::NotFound` so client integrations
            // (`fdev`, `apps/freenet-ping`, integration tests) can
            // distinguish "contract genuinely absent" from "operation
            // failed". Log the cause — silently discarding it made the
            // empty-ring bootstrap failure invisible (#4361).
            tracing::info!(
                tx = %client_tx,
                %instance_id,
                ring_connections = op_manager.ring.connection_manager.connection_count(),
                %cause,
                "GET client: retry loop exhausted — returning NotFound to client"
            );
            Ok(DriverOutcome::Publish(Ok(HostResponse::ContractResponse(
                freenet_stdlib::client_api::ContractResponse::NotFound { instance_id },
            ))))
        }
        RetryLoopOutcome::Unexpected => Err(OpError::UnexpectedOpState),
        RetryLoopOutcome::InfraError(err) => Err(err),
    }
}

// --- Retry-driver state and classification ---

struct GetRetryDriver<'a> {
    op_manager: &'a OpManager,
    instance_id: ContractInstanceId,
    htl: usize,
    tried: Vec<std::net::SocketAddr>,
    retries: usize,
    current_target: PeerKeyLocation,
    attempt_visited: VisitedPeers,
    /// Wall-clock at the start of the most recent `build_request` call.
    /// Paired with `response_received_at` (captured in `classify`) to
    /// feed `time_to_response_start` into the router's isotonic
    /// regression. The winning attempt's values are used. `tokio::time::Instant`
    /// is auto-paused in test builds with `start_paused(true)`, so
    /// simulation tests see virtual elapsed time rather than wall-clock —
    /// matches the rest of `crates/core/`'s timing primitives.
    request_sent_at: Option<tokio::time::Instant>,
    /// Wall-clock when `classify` last returned a `Terminal` outcome.
    /// Reset to `None` until a terminal arrives; non-terminal classify
    /// outcomes (Retry / Unexpected) leave it untouched and the next
    /// `build_request` overwrites `request_sent_at`.
    response_received_at: Option<tokio::time::Instant>,
}

/// Terminal value for the GET driver.
///
/// Carries the bytes needed to (a) store the contract in the local
/// executor via `PutQuery` — matching the side effect that the legacy
/// `process_message` Response{Found} branch performs at
/// `get.rs:2329` — and (b) build the client-facing
/// `HostResponse::GetResponse`.
#[derive(Debug)]
enum Terminal {
    /// Inline Response{Found}: state and optional contract arrived in
    /// the reply envelope; driver stores them locally via PutQuery.
    InlineFound {
        key: ContractKey,
        state: WrappedState,
        contract: Option<ContractContainer>,
        /// Forward-path hop count from the originating Request to the
        /// storer, as carried on the wire Response. Preserved across the
        /// relay bubble-up chain (relays do NOT increment on the return
        /// path). Used by tracing to populate `GetSuccess.hop_count`.
        hop_count: usize,
    },
    /// ResponseStreaming: the envelope references a stream_id whose
    /// bytes arrive separately via the orphan stream registry. The
    /// driver claims the stream, awaits assembly, and caches the
    /// assembled state + contract locally — mirroring what the
    /// legacy `process_message` streaming branch does at
    /// `get.rs:2721-3196`. `total_size` carries the wire-authoritative
    /// payload byte count from the streaming header so the driver
    /// doesn't have to re-query the store post-assembly (which would
    /// race a concurrent UPDATE for the same contract).
    Streaming {
        key: ContractKey,
        stream_id: StreamId,
        includes_contract: bool,
        total_size: u64,
    },
    /// Request-echo from `forward_pending_op_result_if_completed` —
    /// state was already in the local store (via the pre-send
    /// local-cache shortcut), so no new PutQuery is needed. The
    /// driver just resolves the key from the store.
    LocalCompletion,
}

/// Classify a reply into a driver outcome. Extracted from the
/// `RetryDriver::classify` impl so it's reachable from unit tests.
fn classify(reply: NetMessage) -> AttemptOutcome<Terminal> {
    match reply {
        NetMessage::V1(NetMessageV1::Get(GetMsg::Response {
            result:
                GetMsgResult::Found {
                    key,
                    value:
                        StoreResponse {
                            state: Some(state),
                            contract,
                        },
                },
            hop_count,
            ..
        })) => AttemptOutcome::Terminal(Terminal::InlineFound {
            key,
            state,
            contract,
            hop_count,
        }),
        NetMessage::V1(NetMessageV1::Get(GetMsg::Response {
            result: GetMsgResult::Found { value, .. },
            ..
        })) => {
            tracing::warn!(?value, "get: Response{{Found}} arrived without state");
            AttemptOutcome::Unexpected
        }
        NetMessage::V1(NetMessageV1::Get(GetMsg::Response {
            result: GetMsgResult::NotFound,
            ..
        })) => AttemptOutcome::Retry,
        NetMessage::V1(NetMessageV1::Get(GetMsg::ResponseStreaming {
            key,
            stream_id,
            includes_contract,
            total_size,
            ..
        })) => AttemptOutcome::Terminal(Terminal::Streaming {
            key,
            stream_id,
            includes_contract,
            total_size,
        }),
        NetMessage::V1(NetMessageV1::Get(GetMsg::Request { .. })) => {
            AttemptOutcome::Terminal(Terminal::LocalCompletion)
        }
        // Explicit non-terminal `GetMsg` variants. These should never
        // reach the driver — the bypass at
        // `node.rs::handle_pure_network_message_v1` gates forwarding
        // on terminal variants only — so their arrival here
        // indicates a bug in the bypass gate.
        NetMessage::V1(NetMessageV1::Get(
            GetMsg::ForwardingAck { .. } | GetMsg::ResponseStreamingAck { .. },
        )) => AttemptOutcome::Unexpected,
        // Non-GET NetMessage variants (or any future `GetMsg` variant
        // added without updating this match) fall through to
        // Unexpected. If a new GetMsg variant is added, this arm must
        // be audited — this driver has explicit handling for every
        // variant above, and the bypass filter in node.rs must be
        // extended in lockstep.
        _ => AttemptOutcome::Unexpected,
    }
}

impl RetryDriver for GetRetryDriver<'_> {
    type Terminal = Terminal;

    fn new_attempt_tx(&mut self) -> Transaction {
        let tx = Transaction::new::<GetMsg>();
        self.attempt_visited = VisitedPeers::new(&tx);
        // Bootstrap fallback failover (#4361): the wire target for a
        // client GET is re-picked per attempt by the originator-loopback
        // relay, whose selection state is fresh each attempt. Without
        // carrying the client's tried set into the new attempt's visited
        // bloom, every retry would re-select the same first configured
        // gateway — the client-side advance's "next gateway" pick would
        // never reach the wire and multi-gateway failover would be
        // bookkeeping only. Carry `tried` minus the current target (which
        // IS this attempt's intended destination) so the relay's fallback
        // skips gateways that already failed and converges on the same
        // gateway the client driver selected — keeping stream claims and
        // route telemetry (both attributed via `current_target`) aligned
        // with the actual wire hop.
        //
        // The carried bloom travels the attempt's entire forward path, so
        // a failed gateway is excluded at every hop of that attempt, not
        // only at the loopback relay — bounded (empty-ring originators,
        // <= MAX_RETRIES attempts) and re-keyed each retry.
        //
        // Gated on the empty-ring case so normal-path retry routing
        // semantics are unchanged. The gate re-reads `connection_count()`
        // and can race ring promotion between attempts; both directions
        // degrade to a single wasted or spuriously-failed attempt (never
        // a loop or hang) — see the #4364 review for the trace.
        if self.op_manager.ring.connection_manager.connection_count() == 0 {
            carry_tried_into_visited(
                &mut self.attempt_visited,
                &self.tried,
                self.current_target.socket_addr(),
            );
        }
        tx
    }

    fn build_request(&mut self, attempt_tx: Transaction) -> NetMessage {
        // Capture send time per attempt. The winning attempt's timestamp
        // is read after the retry loop returns to compute
        // `time_to_response_start` for routing-prediction telemetry.
        self.request_sent_at = Some(tokio::time::Instant::now());
        NetMessage::from(GetMsg::Request {
            id: attempt_tx,
            instance_id: self.instance_id,
            fetch_contract: true,
            htl: self.htl,
            visited: self.attempt_visited.clone(),
            subscribe: false,
        })
    }

    fn classify(&mut self, reply: NetMessage) -> AttemptOutcome<Terminal> {
        let outcome = classify(reply);
        if matches!(outcome, AttemptOutcome::Terminal(_)) {
            // Only capture on Terminal so non-terminal Retry/Unexpected
            // outcomes leave the field as None until a terminal arrives.
            self.response_received_at = Some(tokio::time::Instant::now());
        }
        outcome
    }

    fn advance(&mut self) -> AdvanceOutcome {
        match advance_to_next_peer(
            self.op_manager,
            &self.instance_id,
            &mut self.tried,
            &mut self.retries,
        ) {
            Some((next_target, _next_addr)) => {
                self.current_target = next_target;
                AdvanceOutcome::Next
            }
            None => AdvanceOutcome::Exhausted,
        }
    }
}

// --- Assembly-retry wrapper (#4345) ---

/// Outcome metadata for the streaming-assembly step of a GET.
#[derive(Default)]
struct AssemblyOutcome {
    /// Wall-clock duration of the successful claim + assemble +
    /// deserialize + local cache write, fed to the router's
    /// transfer-rate estimator. `None` when the terminal was not
    /// `Streaming` or when every assembly attempt failed. The
    /// composite measurement matches what the legacy
    /// `GetStats::record_transfer_end` captured at `get.rs:1542`.
    transfer_duration: Option<std::time::Duration>,
    /// Last assembly failure cause when assembly never succeeded.
    /// Threaded into the synthesized client error so the failure is
    /// diagnosable instead of the generic store-lookup message.
    error: Option<String>,
}

/// Drive the shared GET retry loop, treating stream-assembly failure
/// as a retryable attempt failure (#4345).
///
/// The shared loop classifies the `ResponseStreaming` *header* as
/// terminal (`op_ctx.rs` pins the Terminal arm to return
/// synchronously), so stream assembly necessarily runs after the loop
/// returns. Before this wrapper existed, an assembly failure —
/// fragments lost on a lossy path, the sender aborting on cwnd-wait
/// timeout, a relay's pipe dying after the header was forwarded —
/// burned the whole GET: the driver logged a WARN, fell through to
/// the store re-query, and synthesized a client error with the
/// `MAX_RETRIES` budget untouched. One transport hiccup failed the op
/// even though other candidates could serve it. The relay driver
/// already treats header-without-stream as a retryable routing
/// failure (`drive_relay_get_inner`'s claim-failure `continue`); this
/// gives the originator the same semantics.
///
/// On assembly failure the wrapper advances the driver to the next
/// candidate (consuming the shared retry budget) and re-enters the
/// loop with a fresh attempt transaction — reusing the previous tx
/// would collide with the relay dedup gates (`active_relay_get_txs`)
/// while the failed attempt's relay chain is still draining.
///
/// Once a streaming header has been seen, exhaustion can never surface
/// as `Exhausted` (which callers map to a false `NotFound` for a
/// contract that provably exists). Both exhaustion shapes are covered:
/// the assembly-time `advance()` exhaustion keeps the original
/// `Done(Streaming)` outcome, and a wire exhaustion on a re-entered
/// loop (every remaining candidate NotFound / timeout) is converted
/// back to the remembered `Done(Streaming)` header. Either way the
/// client sees an operation error carrying the assembly cause.
async fn drive_get_with_assembly_retry(
    op_manager: &OpManager,
    first_tx: Transaction,
    op_label: &str,
    driver: &mut GetRetryDriver<'_>,
    emit_route_failure_on_retry: bool,
) -> (RetryLoopOutcome<Terminal>, AssemblyOutcome) {
    let mut attempt_tx = first_tx;
    let mut assembly = AssemblyOutcome::default();
    // Streaming-header fields remembered across an assembly-failure
    // retry. A header proves the contract exists, so if the re-entered
    // loop then exhausts on the wire (every remaining candidate
    // NotFound / timeout), the exhaustion must NOT surface as a false
    // `NotFound` to the client — convert it back to the remembered
    // `Done(Streaming)` so the caller synthesizes an operation error
    // carrying the assembly cause. Pre-#4345 this state was
    // unreachable (assembly failure never re-entered the loop).
    let mut failed_header: Option<(ContractKey, StreamId, bool, u64)> = None;

    let outcome = loop {
        let result = drive_retry_loop(op_manager, attempt_tx, op_label, driver).await;

        // Only a streaming terminal has a post-loop assembly step;
        // everything else passes through unchanged. Match by reference
        // (the fields are all Copy) so `result` stays whole — every
        // give-up exit below is then `break result`, returning the
        // original `Done(Streaming)` outcome without rebuilding it.
        let (key, stream_id, includes_contract, total_size) = match &result {
            RetryLoopOutcome::Done(Terminal::Streaming {
                key,
                stream_id,
                includes_contract,
                total_size,
            }) => (*key, *stream_id, *includes_contract, *total_size),
            RetryLoopOutcome::Done(Terminal::InlineFound { .. } | Terminal::LocalCompletion) => {
                // A non-streaming terminal delivered the state inline,
                // so any earlier assembly failure is moot — clear the
                // remembered error or an unrelated store-lookup miss
                // (eviction race) would be mislabeled as an assembly
                // failure by the caller's error synthesis.
                assembly.error = None;
                break result;
            }
            RetryLoopOutcome::Exhausted(cause) => {
                if let Some((key, stream_id, includes_contract, total_size)) = failed_header {
                    let prior = assembly.error.take().unwrap_or_default();
                    assembly.error = Some(format!(
                        "{prior}; retries after assembly failure exhausted: {cause}"
                    ));
                    // The remembered header's `response_received_at`
                    // belongs to the FIRST attempt, while
                    // `request_sent_at` was overwritten by the last
                    // (exhausted) attempt — the pair is incoherent, and
                    // leaving it set makes the caller's received<sent
                    // guard fire its "clock-source regression" WARN on
                    // every conversion. Clear both so the caller's
                    // timed-outcome capture falls through to None.
                    driver.request_sent_at = None;
                    driver.response_received_at = None;
                    break RetryLoopOutcome::Done(Terminal::Streaming {
                        key,
                        stream_id,
                        includes_contract,
                        total_size,
                    });
                }
                break result;
            }
            RetryLoopOutcome::Unexpected | RetryLoopOutcome::InfraError(_) => break result,
        };

        // Uses `current_target` as the sender address — accurate for
        // the single-hop response case where the responder equals the
        // selected target; relays pipe the stream hop-by-hop so the
        // fragments arrive from the adjacent hop either way.
        let Some(peer_addr) = driver.current_target.socket_addr() else {
            tracing::warn!(
                %key,
                "get: current_target has no socket_addr; \
                 cannot claim orphan stream"
            );
            assembly.error = Some(
                "selected target has no socket address; \
                 cannot claim the response stream"
                    .to_string(),
            );
            break result;
        };

        let stream_start = tokio::time::Instant::now();
        match assemble_and_cache_stream(op_manager, peer_addr, stream_id, key, includes_contract)
            .await
        {
            Ok(()) => {
                assembly.transfer_duration = Some(stream_start.elapsed());
                assembly.error = None;
                break result;
            }
            Err(e) => {
                // Capture the failing peer BEFORE advance() replaces
                // `current_target` — the routing penalty must land on
                // the candidate whose header never became a stream.
                let failed_target = driver.current_target.clone();
                match driver.advance() {
                    AdvanceOutcome::Next => {
                        tracing::warn!(
                            %key,
                            error = %e,
                            retries = driver.retries,
                            "get: stream assembly failed; \
                             retrying against next candidate (#4345)"
                        );
                        // Penalize the failed candidate so the router
                        // learns (mirrors the relay driver's
                        // claim-failure handling). Only on the
                        // advancing path: when the budget is
                        // exhausted, the caller's final route event
                        // (driven by the failed host_result) already
                        // records the Failure for the last target —
                        // emitting here too would double-count it.
                        if emit_route_failure_on_retry {
                            emit_get_route_failure(op_manager, attempt_tx, &failed_target, &key)
                                .await;
                        }
                        #[cfg(any(test, feature = "testing"))]
                        assembly_fault_injection::ASSEMBLY_RETRY_COUNT
                            .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
                        assembly.error = Some(e);
                        // Remember the header so a later wire
                        // exhaustion converts back to Done(Streaming)
                        // instead of surfacing a false NotFound.
                        failed_header = Some((key, stream_id, includes_contract, total_size));
                        attempt_tx = driver.new_attempt_tx();
                        continue;
                    }
                    AdvanceOutcome::Exhausted => {
                        tracing::warn!(
                            %key,
                            error = %e,
                            "get: stream assembly failed and retry budget \
                             exhausted — state will not be cached locally"
                        );
                        assembly.error = Some(e);
                        break result;
                    }
                }
            }
        }
    };

    (outcome, assembly)
}

/// Emit a routing-failure observation for a candidate whose streaming
/// header never became a completed stream. Mirrors the route-event
/// emission in `drive_client_get_inner`'s final outcome block.
async fn emit_get_route_failure(
    op_manager: &OpManager,
    tx: Transaction,
    peer: &PeerKeyLocation,
    key: &ContractKey,
) {
    let route_event = RouteEvent {
        peer: peer.clone(),
        contract_location: Location::from(key),
        outcome: RouteOutcome::Failure,
        op_type: Some(crate::node::network_status::OpType::Get),
    };
    if let Some(log_event) =
        crate::tracing::NetEventLog::route_event(&tx, &op_manager.ring, &route_event)
    {
        op_manager
            .ring
            .register_events(either::Either::Left(log_event))
            .await;
    }
    op_manager.ring.routing_finished(route_event);
}

/// Test-only fault injection for `assemble_and_cache_stream` (#4345).
///
/// Keyed by `ContractKey` so concurrently-running tests in the same
/// process cannot consume each other's injection budget. A test arms
/// `n` failures for its own (unique) contract key; the first `n`
/// assembly attempts for that key fail with a synthetic error,
/// exercising the driver's assembly-retry path deterministically.
#[cfg(any(test, feature = "testing"))]
pub mod assembly_fault_injection {
    use freenet_stdlib::prelude::ContractKey;
    use std::collections::HashMap;
    use std::sync::atomic::AtomicUsize;
    use std::sync::{Mutex, OnceLock};

    /// Lifetime count of assembly-failure retries actually taken by
    /// GET drivers (incremented when the driver advances to the next
    /// candidate after an assembly failure). Tests snapshot
    /// before/after to prove the retry path genuinely fired.
    pub static ASSEMBLY_RETRY_COUNT: AtomicUsize = AtomicUsize::new(0);

    fn budgets() -> &'static Mutex<HashMap<ContractKey, usize>> {
        static BUDGETS: OnceLock<Mutex<HashMap<ContractKey, usize>>> = OnceLock::new();
        BUDGETS.get_or_init(|| Mutex::new(HashMap::new()))
    }

    /// Arm `n` injected assembly failures for `key`.
    pub fn inject_failures(key: ContractKey, n: usize) {
        budgets().lock().expect("poisoned").insert(key, n);
    }

    /// Consume one injected failure for `key`, if armed.
    pub(crate) fn consume(key: &ContractKey) -> bool {
        let mut map = budgets().lock().expect("poisoned");
        match map.get_mut(key) {
            Some(n) if *n > 0 => {
                *n -= 1;
                if *n == 0 {
                    map.remove(key);
                }
                true
            }
            _ => false,
        }
    }
}

// --- Host-response construction ---

/// Query the local contract store for `(state, contract)` and package
/// a client-facing `HostResponse::ContractResponse::GetResponse`.
///
/// If the local store doesn't have the state (which should not happen
/// on the happy path — `process_message` stores before the terminal
/// reply fires), synthesize an operation error matching the shape
/// `to_host_result` produces on NotFound.
///
/// `assembly_error` carries the last stream-assembly failure cause when
/// the streaming path exhausted its retry budget without ever caching
/// the state (#4345). It makes the synthesized client error diagnostic
/// — "stream assembly failed: …" — instead of the generic store-lookup
/// message that conflates assembly failures with eviction races.
async fn build_host_response(
    op_manager: &OpManager,
    instance_id: &ContractInstanceId,
    return_contract_code: bool,
    assembly_error: Option<&str>,
) -> HostResult {
    let lookup = op_manager
        .notify_contract_handler(ContractHandlerEvent::GetQuery {
            instance_id: *instance_id,
            return_contract_code,
        })
        .await;

    match lookup {
        Ok(ContractHandlerEvent::GetResponse {
            key: Some(resolved_key),
            response:
                Ok(StoreResponse {
                    state: Some(state),
                    contract,
                }),
        }) => {
            // Strip contract code if client didn't ask for it. The
            // node always pulls WASM for local caching/validation,
            // but the client-facing payload obeys their flag.
            let client_contract = if return_contract_code { contract } else { None };
            Ok(HostResponse::ContractResponse(
                ContractResponse::GetResponse {
                    key: resolved_key,
                    contract: client_contract,
                    state,
                },
            ))
        }
        _ => {
            let cause = synthesized_get_error_cause(instance_id, assembly_error);
            tracing::warn!(
                contract = %instance_id,
                %cause,
                "get: terminal reply classified success but local \
                 store lookup returned no state; synthesizing client error"
            );
            Err(ErrorKind::OperationError {
                cause: cause.into(),
            }
            .into())
        }
    }
}

/// Fallback `ContractKey` for telemetry when we have neither a
/// remote-reply key nor a store-resolved key. Zero code-hash is the
/// documented sentinel — routing telemetry only needs a `Location`
/// derived from the instance_id, which is preserved here.
fn synthetic_key(instance_id: &ContractInstanceId) -> ContractKey {
    ContractKey::from_id_and_code(*instance_id, CodeHash::new([0u8; 32]))
}

/// Store the fetched contract state in the local executor and run
/// the originator-side hosting side effects. Mirrors the legacy
/// `process_message` Response{Found} branch at `get.rs:2218-2450`:
///
/// 1. **Idempotency short-circuit (issue #2018)** — re-query the
///    local store first. If the existing bytes match the incoming
///    state, skip `PutQuery` entirely so contracts that enforce
///    identical-state rejection in `update_state()` aren't invoked
///    redundantly.
/// 2. **Unconditional hosting refresh** — `record_get_access` and
///    interest-manager eviction cleanup run for BOTH the
///    state-matches short-circuit AND the PutQuery-failed error paths.
///    Legacy behaviour at `get.rs:2420-2435` continues these side
///    effects on error so re-GETs keep refreshing the hosting LRU/TTL
///    even when the executor rejected the write.
/// 3. **`mark_local_client_access` gated on `is_client_requester`** —
///    the sticky flag that moves the contract into the
///    `contracts_needing_renewal()` set (see `ring/hosting.rs:889`) must
///    only fire when THIS node is the client-originating requester.
///    Relay peers that merely cache a forwarded Found MUST NOT set it,
///    or they permanently pay subscription-renewal cost for contracts
///    no client on this node ever asked for. Legacy mirror:
///    `get.rs:2260-2262, :2353-2355, :3056-3058`
///    all gate the call on `is_original_requester =
///    upstream_addr.is_none()`.
/// 4. **Newly-hosted announcement** — only runs when the local
///    store actually transitioned from no-state to has-state
///    (i.e., `access_result.is_new && put_persisted`). NOT gated on
///    `is_client_requester`; legacy announces on any first-time relay
///    cache too (`get.rs:2278, 2370`).
async fn cache_contract_locally(
    op_manager: &OpManager,
    key: ContractKey,
    state: WrappedState,
    contract: Option<ContractContainer>,
    is_client_requester: bool,
) {
    let state_size = state.size() as u64;

    // (1) Idempotency short-circuit: re-query the local store FIRST.
    // Comparing bytes against the incoming state avoids re-invoking
    // `update_state()` in contracts that reject identical updates
    // (regression guard for issue #2018 / PR #2018).
    let local_state = op_manager
        .notify_contract_handler(ContractHandlerEvent::GetQuery {
            instance_id: *key.id(),
            return_contract_code: false,
        })
        .await;
    let state_matches = matches!(
        &local_state,
        Ok(ContractHandlerEvent::GetResponse {
            response: Ok(StoreResponse {
                state: Some(local),
                ..
            }),
            ..
        }) if local.as_ref() == state.as_ref(),
    );

    // (2) Decide whether PutQuery must run. If local state already
    // matches or we lack the contract code (issue #2306), skip the
    // PutQuery but STILL run hosting side effects below so LRU/TTL
    // refresh does not depend on the write path.
    let put_persisted = if state_matches {
        tracing::debug!(
            %key,
            "get: local state matches, skipping redundant PutQuery"
        );
        false
    } else if let Some(contract_code) = contract {
        match op_manager
            .notify_contract_handler(ContractHandlerEvent::PutQuery {
                key,
                state,
                related_contracts: RelatedContracts::default(),
                contract: Some(contract_code),
            })
            .await
        {
            Ok(ContractHandlerEvent::PutResponse {
                new_value: Ok(_), ..
            }) => true,
            Ok(ContractHandlerEvent::PutResponse {
                new_value: Err(err),
                ..
            }) => {
                tracing::warn!(
                    %key,
                    %err,
                    "get: PutQuery rejected by executor"
                );
                false
            }
            Ok(other) => {
                tracing::warn!(
                    %key,
                    ?other,
                    "get: PutQuery returned unexpected event"
                );
                false
            }
            Err(err) => {
                tracing::warn!(
                    %key,
                    %err,
                    "get: PutQuery failed"
                );
                false
            }
        }
    } else {
        // No contract code + state differs — we can't cache (issue #2306).
        // Still refresh hosting side effects below so re-GET TTL bookkeeping
        // isn't gated on the write path.
        tracing::debug!(
            %key,
            "get: skipping local cache — contract code missing"
        );
        false
    };

    // (3) Hosting side effects ALWAYS run (state_matches, put_persisted,
    // or put failed). This mirrors the legacy invariant that a
    // successful wire-level GET must refresh the hosting LRU/TTL
    // regardless of what the local executor did with the state.
    let access_result = op_manager.ring.record_get_access(key, state_size);
    // Sticky flag gating subscription renewal; only the client-originating
    // node sets it. Relays that pass through a Found MUST NOT taint their
    // own hosting cache with another node's client access. Legacy mirror:
    // get.rs:2260-2262 / :2353-2355 / :3056-3058 all guard on
    // `is_original_requester = upstream_addr.is_none()`.
    if is_client_requester {
        op_manager.ring.mark_local_client_access(&key);
    }

    let mut removed_contracts = Vec::new();
    for (evicted_key, expected_generation) in &access_result.evicted {
        if op_manager
            .interest_manager
            .unregister_local_hosting(evicted_key)
        {
            removed_contracts.push(*evicted_key);
        }
        // Reclaim on-disk storage for the evicted contract so the hosting
        // budget is a real disk bound (subscription- and generation-gated
        // inside the helper).
        crate::operations::reclaim_evicted_contract(op_manager, *evicted_key, *expected_generation);
    }

    // (4) Newly-hosted announcement gates on BOTH first-time access
    // AND the fact that we actually persisted new state. Without
    // persistence there's nothing to announce hosting for.
    if access_result.is_new && put_persisted {
        crate::operations::announce_contract_hosted(op_manager, &key).await;
        // Directed-subscribe placement (#4404): best-effort nudge the node to
        // consider migrating this freshly-hosted contract toward a closer
        // neighbor. Dropped silently if the event channel is full — the next
        // hosting/peer event re-triggers consideration.
        if let Err(err) =
            op_manager.try_notify_node_event(NodeEvent::ConsiderContractMigration { key })
        {
            tracing::debug!(%key, %err, "ConsiderContractMigration emit dropped (GET)");
        }
        let became_interested = op_manager.interest_manager.register_local_hosting(&key);
        let added = if became_interested { vec![key] } else { vec![] };
        if !added.is_empty() || !removed_contracts.is_empty() {
            crate::operations::broadcast_change_interests(op_manager, added, removed_contracts)
                .await;
        }
    } else if !removed_contracts.is_empty() {
        crate::operations::broadcast_change_interests(op_manager, vec![], removed_contracts).await;
    }
}

/// Claim an orphan stream, await assembly, deserialize the payload,
/// and cache the contract state locally.
///
/// Mirrors the originator-side streaming branch of the legacy
/// `process_message` at `get.rs:2721-3196`. The driver is the only
/// place this can run for driver GETs because the bypass at
/// `node.rs::handle_pure_network_message_v1` forwards the
/// `ResponseStreaming` envelope to the driver before
/// `handle_op_request` — `process_message` never executes on the
/// originator for driver ops (`load_or_init` would return
/// `OpNotPresent`).
///
/// `peer_addr` is the sender's transport address — we use
/// `driver.current_target.socket_addr()`. Multi-hop streamed GET IS now
/// supported: relays fork+pipe the stream and re-key it with a fresh
/// outbound `stream_id` per hop (#4307), so the originator always claims
/// the stream keyed by its `current_target` (the immediate next hop),
/// regardless of how many relays the response traversed. See #3883.
async fn assemble_and_cache_stream(
    op_manager: &OpManager,
    peer_addr: std::net::SocketAddr,
    stream_id: StreamId,
    expected_key: ContractKey,
    includes_contract: bool,
) -> Result<(), String> {
    // Test-only deterministic fault injection (#4345). Returning before
    // the claim mirrors the production failure (the inbound stream is
    // left orphaned for GC), so the retry path is exercised end-to-end.
    #[cfg(any(test, feature = "testing"))]
    if assembly_fault_injection::consume(&expected_key) {
        return Err("injected stream assembly failure (assembly_fault_injection test hook)".into());
    }

    let handle = match op_manager
        .orphan_stream_registry()
        .claim_or_wait(peer_addr, stream_id, STREAM_CLAIM_TIMEOUT)
        .await
    {
        Ok(h) => h,
        Err(OrphanStreamError::AlreadyClaimed) => {
            tracing::debug!(
                %peer_addr,
                %stream_id,
                "stream already claimed (dedup)"
            );
            return Ok(());
        }
        Err(e) => return Err(format!("claim_or_wait: {e}")),
    };

    let bytes = handle
        .assemble()
        .await
        .map_err(|e| format!("stream assembly: {e}"))?;

    let payload: GetStreamingPayload =
        bincode::deserialize(&bytes).map_err(|e| format!("deserialize: {e}"))?;

    if payload.key != expected_key {
        return Err(format!(
            "stream key mismatch: expected {expected_key}, got {}",
            payload.key
        ));
    }

    let Some(state) = payload.value.state else {
        return Err("stream payload has no state".into());
    };

    let contract = if includes_contract {
        payload.value.contract
    } else {
        None
    };

    // This helper runs on the client-driver (originator) side. The relay
    // driver also claims streams now (the `Terminal::Streaming` arm, #4307),
    // but it uses its own inline assemble+cache with `local_client_access =
    // false`; this path is the originator, which IS the client requester, so
    // the sticky `local_client_access` flag applies here.
    cache_contract_locally(op_manager, payload.key, state, contract, true).await;
    Ok(())
}

/// Re-query the local store for the contract key, used on the
/// LocalCompletion path where the Request echo carries only an
/// instance_id.
async fn lookup_stored_key(
    op_manager: &OpManager,
    instance_id: &ContractInstanceId,
) -> Option<ContractKey> {
    let lookup = op_manager
        .notify_contract_handler(ContractHandlerEvent::GetQuery {
            instance_id: *instance_id,
            return_contract_code: false,
        })
        .await;

    match lookup {
        Ok(ContractHandlerEvent::GetResponse {
            key: Some(key),
            response: Ok(_),
        }) => Some(key),
        _ => None,
    }
}

// --- Peer advance ---

/// Maximum routing rounds before giving up. Matches PUT's
/// `MAX_PEER_ADVANCEMENTS_NON_STREAMING = 3` and SUBSCRIBE's driver.
/// With typical ring fan-out of 3–5 peers per k_closest call, 3
/// rounds covers 9–15 distinct peers. GET kept the legacy
/// `MAX_RETRIES` name because (a) GETs are never streaming today
/// (no large-payload class on the wire), so the streaming/non-
/// streaming split PUT needed doesn't apply, and (b) renaming would
/// touch unrelated code paths.
const MAX_RETRIES: usize = 3;

/// Pure selection core for the bootstrap gateway fallback (#4361).
///
/// Returns the first configured gateway that is not this node and not
/// excluded by the caller's skip predicate — but ONLY when the ring is
/// empty (`ring_connection_count == 0`). A non-empty ring means normal
/// routing had ring entries to consider (its candidates may still all
/// be filtered as transient/visited, but that exhaustion is genuine),
/// so the fallback must stay out of the way.
///
/// Selection is deliberately deterministic (config order), unlike the
/// randomized pick in #3219's CONNECT re-bootstrap: the client driver
/// and the per-attempt loopback relay select independently and must
/// converge on the same gateway given the same exclusion set — stream
/// claims and route telemetry are attributed via the client's
/// `current_target`, so divergence would mis-key both. Failover
/// diversity comes from the exclusion predicate (tried/visited), not
/// from randomization.
///
/// Split out from [`bootstrap_gateway_target`] so unit tests can
/// exercise the selection rules without constructing an `OpManager`.
fn select_bootstrap_gateway(
    ring_connection_count: usize,
    configured_gateways: &[PeerKeyLocation],
    own_addr: Option<SocketAddr>,
    is_excluded: impl Fn(SocketAddr) -> bool,
) -> Option<(PeerKeyLocation, SocketAddr)> {
    if ring_connection_count > 0 {
        return None;
    }
    configured_gateways.iter().find_map(|gw| {
        let addr = gw.socket_addr()?;
        if Some(addr) == own_addr || is_excluded(addr) {
            return None;
        }
        Some((gw.clone(), addr))
    })
}

/// Carry the client driver's tried set into a fresh attempt's visited
/// bloom, excluding the attempt's intended destination (#4361 / #4364
/// review H1). Split out so unit tests can pin the exclusion behavior
/// without constructing an `OpManager`:
///
/// - dropping the carry entirely resurrects the "failover never reaches
///   the wire" bug (the per-attempt loopback relay re-picks the first
///   configured gateway forever);
/// - dropping the current-target exclusion makes single-gateway retries
///   exhaust instantly (the relay would skip the client's own pick).
fn carry_tried_into_visited(
    visited: &mut VisitedPeers,
    tried: &[SocketAddr],
    current_target_addr: Option<SocketAddr>,
) {
    for addr in tried {
        if Some(*addr) != current_target_addr {
            visited.mark_visited(*addr);
        }
    }
}

/// Bootstrap gateway fallback (#4361).
///
/// A node whose ring is still empty (`connections_by_location` has no
/// entries) has zero routing candidates, so without a fallback every
/// GET fails instantly with NotFound — even though the node has a live
/// transient transport connection to its gateway (the same connection
/// its CONNECT handshake is negotiating over). Production analog: a
/// freshly started node fails all GETs for its first minutes until
/// ring promotion completes.
///
/// When the ring is empty, fall back to a configured gateway. Wire
/// delivery works before ring promotion: the event loop's
/// `OutboundMessageWithTarget` handler resolves targets by socket addr
/// against the transport map (which includes transient connections)
/// and re-dials configured gateways if the transport lapsed. Mirrors
/// the #3219 zero-connection CONNECT re-bootstrap shape, which gates
/// on the same `connection_count() == 0` condition.
///
/// Tradeoff for genuinely unreachable gateways (e.g. an offline
/// machine): a dial failure is not surfaced to the waiting driver, so
/// each attempt waits its full per-attempt timeout (`OPERATION_TTL`,
/// 60s) before advancing — up to ~3 minutes across the retry budget,
/// where the pre-fallback behavior returned NotFound instantly. The
/// instant NotFound was a false "contract absent" answer, so slower
/// but honest is preferred; a distinct fail-fast "not bootstrapped /
/// unreachable" client error is #4166's scope.
fn bootstrap_gateway_target(
    op_manager: &OpManager,
    is_excluded: impl Fn(SocketAddr) -> bool,
) -> Option<(PeerKeyLocation, SocketAddr)> {
    select_bootstrap_gateway(
        op_manager.ring.connection_manager.connection_count(),
        &op_manager.configured_gateways,
        op_manager.ring.connection_manager.get_own_addr(),
        is_excluded,
    )
}

fn advance_to_next_peer(
    op_manager: &OpManager,
    instance_id: &ContractInstanceId,
    tried: &mut Vec<std::net::SocketAddr>,
    retries: &mut usize,
) -> Option<(PeerKeyLocation, std::net::SocketAddr)> {
    if *retries >= MAX_RETRIES {
        return None;
    }
    *retries += 1;

    let peer = match op_manager
        .ring
        .k_closest_potentially_hosting(instance_id, tried.as_slice(), 1)
        .into_iter()
        .next()
    {
        Some(peer) => peer,
        None => {
            // Bootstrap fallback (#4361): empty ring → route via a
            // configured gateway instead of silently exhausting.
            return match bootstrap_gateway_target(op_manager, |addr| tried.contains(&addr)) {
                Some((gw, addr)) => {
                    tracing::info!(
                        %instance_id,
                        gateway = %addr,
                        "GET advance: ring empty — falling back to configured gateway"
                    );
                    tried.push(addr);
                    Some((gw, addr))
                }
                None => {
                    tracing::debug!(
                        %instance_id,
                        tried = tried.len(),
                        retries = *retries,
                        "GET advance: no routing candidates — exhausted"
                    );
                    None
                }
            };
        }
    };
    let Some(addr) = peer.socket_addr() else {
        // Rare but possible — `k_closest_potentially_hosting` can return
        // addressless candidates (ring.rs pushes them past the addr-gated
        // filters), and an addressless pick is unusable as a wire target.
        tracing::warn!(
            %instance_id,
            peer = ?peer,
            "GET advance: selected routing candidate has no socket address — treating as exhausted"
        );
        return None;
    };
    tried.push(addr);
    Some((peer, addr))
}

// --- Subscribe child ---

/// Start a post-GET subscription if requested. Mirrors
/// `put::op_ctx_task::maybe_subscribe_child` verbatim.
///
/// For `blocking_subscribe = true`, awaits the subscribe driver inline.
/// For `blocking_subscribe = false`, spawns a fire-and-forget task.
async fn maybe_subscribe_child(
    op_manager: &Arc<OpManager>,
    client_tx: Transaction,
    key: ContractKey,
    subscribe: bool,
    blocking_subscribe: bool,
) {
    if !subscribe {
        return;
    }

    use crate::operations::subscribe;

    let child_tx = Transaction::new_child_of::<subscribe::SubscribeMsg>(&client_tx);

    // No SubOperationTracker registration needed: the silent-absorb
    // guards at `p2p_protoc.rs`, `node.rs`, and `subscribe.rs` use the
    // structural `Transaction::is_sub_operation()` check (parent field
    // set by `new_child_of`), not the tracker DashMap.

    if blocking_subscribe {
        subscribe::run_client_subscribe(op_manager.clone(), *key.id(), child_tx).await;
    } else {
        GlobalExecutor::spawn(subscribe::run_client_subscribe(
            op_manager.clone(),
            *key.id(),
            child_tx,
        ));
    }
}

// --- Outcome delivery ---

fn deliver_outcome(op_manager: &OpManager, client_tx: Transaction, outcome: DriverOutcome) {
    match outcome {
        DriverOutcome::Publish(result) => {
            op_manager.send_client_result(client_tx, result);
        }
        DriverOutcome::InfrastructureError(err) => {
            tracing::warn!(
                tx = %client_tx,
                error = %err,
                "get: infrastructure error; publishing synthesized client error"
            );
            let synthesized: HostResult = Err(ErrorKind::OperationError {
                cause: format!("GET failed: {err}").into(),
            }
            .into());
            op_manager.send_client_result(client_tx, synthesized);
        }
    }
}

// ── Sub-operation GET driver ────────────────────────────────────
//
// Entry point for node-internal GETs that have no client (executor's
// `local_state_or_from_network` and subscribe's `fetch_contract_if_missing`).
// Reuses the `GetRetryDriver` retry loop but skips auto-subscribe,
// explicit-subscribe hand-off, telemetry route-event emission, and
// result-router publication. The terminal `(GetResult)` (or error) is
// delivered through a oneshot receiver returned to the caller — fire-and-
// forget callers drop the receiver, awaiting callers (executor) await it.

/// Outcome of a sub-op GET task. `Found` carries the wire-level reply
/// payload assembled into a `GetResult`; `NotFound` indicates retry
/// exhaustion or driver classification miss; `Infra` carries an
/// infrastructure failure (channel closed, OpCtx bug, etc.).
#[derive(Debug)]
pub(crate) enum SubOpGetOutcome {
    Found(crate::operations::get::GetResult),
    NotFound(String),
    Infra(OpError),
}

/// Spawn a sub-operation GET. Returns the transaction id and a
/// oneshot receiver carrying the [`SubOpGetOutcome`]. Callers that
/// just want the side effect of caching the contract locally (e.g.,
/// `subscribe::fetch_contract_if_missing`) may drop the receiver
/// immediately. Callers that need the resolved `GetResult` (e.g.,
/// `executor::local_state_or_from_network`) await the receiver.
pub(crate) fn start_sub_op_get(
    op_manager: &OpManager,
    instance_id: ContractInstanceId,
    return_contract_code: bool,
) -> (Transaction, tokio::sync::oneshot::Receiver<SubOpGetOutcome>) {
    let op_manager = Arc::new(op_manager.clone());

    let tx = Transaction::new::<GetMsg>();
    let (out_tx, out_rx) = tokio::sync::oneshot::channel();

    tracing::debug!(
        %tx,
        contract = %instance_id,
        "get: spawning sub-op task"
    );

    GlobalExecutor::spawn(run_sub_op_get(
        op_manager,
        tx,
        instance_id,
        return_contract_code,
        None,
        Some(out_tx),
    ));

    (tx, out_rx)
}

/// Spawn a sub-operation GET that targets a specific peer for its
/// first hop (the legacy `start_targeted_op` migration site for
/// UPDATE's auto-fetch). Fire-and-forget — the outcome is logged and
/// the caller relies on the side effect (contract cached locally).
///
/// Used by `OpManager::try_auto_fetch_contract` when an UPDATE
/// broadcast fails because the recipient lacks the contract's
/// parameters: the directed target is the UPDATE sender, who is
/// known to host the contract. If the directed peer responds
/// `NotFound`, the retry loop falls back to `k_closest_potentially_hosting`
/// just like a regular sub-op GET.
pub(crate) fn start_targeted_sub_op_get(
    op_manager: &OpManager,
    instance_id: ContractInstanceId,
    target: PeerKeyLocation,
) -> Transaction {
    let op_manager = Arc::new(op_manager.clone());

    let tx = Transaction::new::<GetMsg>();

    tracing::debug!(
        %tx,
        contract = %instance_id,
        ?target,
        "get: spawning targeted sub-op task (UPDATE auto-fetch)"
    );

    GlobalExecutor::spawn(run_sub_op_get(
        op_manager,
        tx,
        instance_id,
        true, // auto-fetch always wants the contract code
        Some(target),
        None,
    ));

    tx
}

async fn run_sub_op_get(
    op_manager: Arc<OpManager>,
    tx: Transaction,
    instance_id: ContractInstanceId,
    return_contract_code: bool,
    initial_target: Option<PeerKeyLocation>,
    out_tx: Option<tokio::sync::oneshot::Sender<SubOpGetOutcome>>,
) {
    // RAII guard: same loopback-cleanup as ClientGetCompletionGuard (#4066).
    let _completion_guard = SubOpGetCompletionGuard {
        op_manager: op_manager.clone(),
        tx,
    };

    let outcome = drive_sub_op_get(
        &op_manager,
        tx,
        instance_id,
        return_contract_code,
        initial_target,
    )
    .await;

    if let Some(out_tx) = out_tx {
        // Receiver drop is acceptable — fire-and-forget callers expect this.
        #[allow(clippy::let_underscore_must_use)]
        let _ = out_tx.send(outcome);
    } else {
        // Fire-and-forget targeted auto-fetch. Log the outcome so operators
        // can correlate UPDATE auto-fetch attempts to success/failure.
        match outcome {
            SubOpGetOutcome::Found(_) => tracing::info!(
                %tx,
                contract = %instance_id,
                "get (driver targeted sub-op): UPDATE auto-fetch succeeded"
            ),
            SubOpGetOutcome::NotFound(cause) => tracing::warn!(
                %tx,
                contract = %instance_id,
                cause,
                "get (driver targeted sub-op): UPDATE auto-fetch did not find state"
            ),
            SubOpGetOutcome::Infra(err) => tracing::warn!(
                %tx,
                contract = %instance_id,
                error = %err,
                "get (driver targeted sub-op): UPDATE auto-fetch hit infra error"
            ),
        }
    }
}

/// RAII guard counterpart to `ClientGetCompletionGuard` for sub-op
/// GET drivers.
struct SubOpGetCompletionGuard {
    op_manager: Arc<OpManager>,
    tx: Transaction,
}

impl Drop for SubOpGetCompletionGuard {
    fn drop(&mut self) {
        self.op_manager.completed(self.tx);
    }
}

async fn drive_sub_op_get(
    op_manager: &Arc<OpManager>,
    tx: Transaction,
    instance_id: ContractInstanceId,
    return_contract_code: bool,
    initial_target: Option<PeerKeyLocation>,
) -> SubOpGetOutcome {
    let htl = op_manager.ring.max_hops_to_live;

    let mut tried: Vec<std::net::SocketAddr> = Vec::new();
    if let Some(own_addr) = op_manager.ring.connection_manager.get_own_addr() {
        tried.push(own_addr);
    }
    let initial_target = initial_target.or_else(|| {
        op_manager
            .ring
            .k_closest_potentially_hosting(&instance_id, tried.as_slice(), 1)
            .into_iter()
            .next()
    });
    let current_target = match initial_target {
        Some(peer) => {
            if let Some(addr) = peer.socket_addr() {
                tried.push(addr);
            }
            peer
        }
        // Bootstrap fallback (#4361) — same rationale as the client
        // driver's initial pick: sub-op GETs (auto-fetch, related-contract
        // fetches) hit the same empty-ring blind spot during bootstrap.
        None => match bootstrap_gateway_target(op_manager, |addr| tried.contains(&addr)) {
            Some((gw, addr)) => {
                tracing::info!(
                    %instance_id,
                    gateway = %addr,
                    "GET sub-op: ring empty — initial target falls back to configured gateway"
                );
                tried.push(addr);
                gw
            }
            None => op_manager.ring.connection_manager.own_location(),
        },
    };

    let mut driver = GetRetryDriver {
        op_manager,
        instance_id,
        htl,
        tried,
        retries: 0,
        current_target,
        attempt_visited: VisitedPeers::new(&tx),
        request_sent_at: None,
        response_received_at: None,
    };

    let (loop_result, streaming_assembly) = drive_get_with_assembly_retry(
        op_manager,
        tx,
        "get-subop",
        &mut driver,
        // Sub-op GETs don't feed the router (no RouteEvent is emitted
        // on the sub-op path), so skip the per-retry failure events.
        /* emit_route_failure_on_retry */
        false,
    )
    .await;

    // `op_manager.completed(tx)` runs from the
    // `SubOpGetCompletionGuard` in `run_sub_op_get` AFTER this fn
    // returns. See the matching comment in `drive_client_get_inner`.

    match loop_result {
        RetryLoopOutcome::Done(terminal) => {
            match &terminal {
                Terminal::InlineFound {
                    key,
                    state,
                    contract,
                    hop_count: _,
                } => {
                    cache_contract_locally(
                        op_manager,
                        *key,
                        state.clone(),
                        contract.clone(),
                        false, // sub-op: not a client-originating GET
                    )
                    .await;
                }
                // Stream assembly (with per-candidate retry, #4345)
                // already ran inside `drive_get_with_assembly_retry`;
                // on persistent failure the store re-query below
                // returns NotFound with the assembly cause attached.
                Terminal::Streaming { .. } => {}
                Terminal::LocalCompletion => {}
            }

            // Resolve a GetResult by re-querying the local store. Mirrors
            // `build_host_response` but returns the raw `GetResult` shape
            // instead of a HostResponse.
            let lookup = op_manager
                .notify_contract_handler(ContractHandlerEvent::GetQuery {
                    instance_id,
                    return_contract_code,
                })
                .await;
            match lookup {
                Ok(ContractHandlerEvent::GetResponse {
                    key: Some(_),
                    response:
                        Ok(StoreResponse {
                            state: Some(state),
                            contract,
                        }),
                }) => {
                    let client_contract = if return_contract_code { contract } else { None };
                    SubOpGetOutcome::Found(crate::operations::get::GetResult::new(
                        state,
                        client_contract,
                    ))
                }
                _ => SubOpGetOutcome::NotFound(sub_op_not_found_cause(
                    &instance_id,
                    streaming_assembly.error.as_deref(),
                )),
            }
        }
        RetryLoopOutcome::Exhausted(cause) => SubOpGetOutcome::NotFound(cause),
        RetryLoopOutcome::Unexpected => SubOpGetOutcome::Infra(OpError::UnexpectedOpState),
        RetryLoopOutcome::InfraError(err) => SubOpGetOutcome::Infra(err),
    }
}

/// Cause string for a client GET whose terminal reply was classified
/// success but whose state never reached the local store. Carries the
/// assembly failure cause when the streaming path exhausted its retry
/// budget (#4345); otherwise the generic store-lookup message (covers
/// eviction races and executor rejections). Pure helper so both arms
/// are unit-testable without a real `OpManager`.
fn synthesized_get_error_cause(
    instance_id: &ContractInstanceId,
    assembly_error: Option<&str>,
) -> String {
    match assembly_error {
        Some(e) => format!(
            "GET response stream assembly failed for {instance_id} \
             after exhausting retries: {e}"
        ),
        None => format!("GET succeeded on wire but local store lookup failed for {instance_id}"),
    }
}

/// Sub-op variant of [`synthesized_get_error_cause`]: the store-miss
/// cause with the assembly failure appended when one occurred (#4345).
fn sub_op_not_found_cause(
    instance_id: &ContractInstanceId,
    assembly_error: Option<&str>,
) -> String {
    match assembly_error {
        Some(e) => format!("{}: {e}", missing_state_cause(instance_id)),
        None => missing_state_cause(instance_id),
    }
}

/// Cause string for a sub-op GET that succeeded on the wire but
/// produced no state in the local store on re-query. Extracted as a
/// pure helper so the message format is unit-testable without a
/// real `OpManager`.
fn missing_state_cause(instance_id: &ContractInstanceId) -> String {
    format!(
        "sub-op GET wire-level success but local store lookup returned no state for {instance_id}"
    )
}

// ── Relay GET driver (#3883) ────────────────────────────────────
//
// `start_relay_get` is the entry point for the relay (non-originator) GET
// driver.  It is called from `node.rs` dispatch (commit 2) when
// an incoming `GetMsg::Request` arrives with `source_addr.is_some()` — i.e.
// from a real remote peer rather than the originator's own loop-back.
//
// The driver owns all routing / forwarding / retry state in task locals.
// No `GetOp` is stored in `OpManager.ops.get` for any relay hop this driver
// handles.  Responses are bubbled back upstream via `OpCtx::send_to_and_await`
// targeting the downstream peer, and the reply (Found / NotFound) is forwarded
// to `upstream_addr` via a fire-and-forget `conn_manager.send`.
//
// ResponseStreaming relay forwarding (chunk pipe-through) IS now implemented
// in the `Terminal::Streaming` arm of `drive_relay_get_inner` (fork + pipe;
// issue #4307). Still out of scope for the driver:
//   - GC-spawned retries.
//   - start_targeted_op (UPDATE-triggered auto-fetch).

/// Start a relay (non-originator) GET driver.
///
/// Called from `node.rs` dispatch when an incoming `GetMsg::Request`
/// arrives from a remote peer (`source_addr.is_some()`).  The driver
/// owns routing/forwarding/retry state in its task locals — no `GetOp`
/// is stored in `OpManager.ops.get` for this transaction.
///
/// Originator loop-back (`source_addr.is_none()`) is mapped by `node.rs`
/// dispatch to `upstream_addr = own_addr` and driven by this same driver
/// (the legacy `process_message` path is deleted); the loopback edge is
/// handled by the safety-net branches that cache locally instead of
/// piping/replying to self.
///
/// # Scope (#3883)
///
/// Migrated:
/// - `GetMsg::Request` relay arm: HTL check, local-cache lookup (with
///   interest gate), forward-or-respond decision.
/// - `GetMsg::Response{NotFound}` retry to next alternative peer.
/// - `GetMsg::Response{Found}` bubble-up to upstream.
/// - `GetMsg::ResponseStreaming` relay forwarding (fork + pipe, #4307).
/// - `ForwardingAck` send-before-forward.
///
/// NOT migrated (stays on legacy path):
/// - GC-spawned retries.
/// - `start_targeted_op` (UPDATE-triggered auto-fetch).
#[allow(clippy::too_many_arguments)]
pub(crate) async fn start_relay_get<CB>(
    op_manager: Arc<OpManager>,
    conn_manager: CB,
    incoming_tx: Transaction,
    instance_id: ContractInstanceId,
    htl: usize,
    upstream_addr: SocketAddr,
    visited: VisitedPeers,
    fetch_contract: bool,
    subscribe: bool,
) -> Result<(), OpError>
where
    CB: NetworkBridge + Clone + Send + 'static,
{
    // Test-only: count relay driver invocations so regression tests can
    // assert the dispatch gate in node.rs actually routed a fresh inbound
    // Request through the driver rather than the legacy
    // `handle_op_request` fallthrough (phase-3b loopback, GC retries,
    // `start_targeted_op`).
    #[cfg(any(test, feature = "testing"))]
    RELAY_DRIVER_CALL_COUNT.fetch_add(1, std::sync::atomic::Ordering::SeqCst);

    // Dedup gate: a relay driver for this incoming_tx is already live on
    // this node. The duplicate inbound Request is a retransmission, GC
    // retry, or routing bloom false-positive — don't spawn a second
    // driver. Returning Ok drops the Request silently (matches legacy
    // semantics where a duplicate Request hitting an in-flight op
    // returned `OpNotAvailable::Running` and was dropped by the caller).
    if !op_manager.active_relay_get_txs.insert(incoming_tx) {
        RELAY_DEDUP_REJECTS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        tracing::debug!(
            tx = %incoming_tx,
            %instance_id,
            %upstream_addr,
            phase = "relay_dedup_reject",
            "GET relay: duplicate Request for in-flight tx, dropping"
        );
        return Ok(());
    }

    tracing::debug!(
        tx = %incoming_tx,
        %instance_id,
        htl,
        %upstream_addr,
        phase = "relay_start",
        "GET relay: spawning driver"
    );

    GlobalExecutor::spawn(run_relay_get(
        op_manager,
        conn_manager,
        incoming_tx,
        instance_id,
        htl,
        upstream_addr,
        visited,
        fetch_contract,
        subscribe,
    ));
    Ok(())
}

/// RAII guard that decrements `RELAY_INFLIGHT`, bumps
/// `RELAY_COMPLETED_TOTAL`, and removes the driver's `incoming_tx`
/// from the per-node dedup set on drop. Using a guard (vs. matching
/// every exit path) keeps the counters and dedup set correct under
/// panics and early returns.
struct RelayInflightGuard {
    op_manager: Arc<OpManager>,
    incoming_tx: Transaction,
}

impl Drop for RelayInflightGuard {
    fn drop(&mut self) {
        self.op_manager
            .active_relay_get_txs
            .remove(&self.incoming_tx);
        RELAY_INFLIGHT.fetch_sub(1, std::sync::atomic::Ordering::Relaxed);
        RELAY_COMPLETED_TOTAL.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
    }
}

#[allow(clippy::too_many_arguments)]
async fn run_relay_get<CB>(
    op_manager: Arc<OpManager>,
    conn_manager: CB,
    incoming_tx: Transaction,
    instance_id: ContractInstanceId,
    htl: usize,
    upstream_addr: SocketAddr,
    visited: VisitedPeers,
    fetch_contract: bool,
    subscribe: bool,
) where
    CB: NetworkBridge + Clone + Send + 'static,
{
    RELAY_INFLIGHT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
    RELAY_SPAWNED_TOTAL.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
    let _guard = RelayInflightGuard {
        op_manager: op_manager.clone(),
        incoming_tx,
    };

    let drive_result = drive_relay_get(
        &op_manager,
        &conn_manager,
        incoming_tx,
        instance_id,
        htl,
        upstream_addr,
        visited,
        fetch_contract,
        subscribe,
    )
    .await;

    if let Err(err) = &drive_result {
        tracing::warn!(
            tx = %incoming_tx,
            %instance_id,
            error = %err,
            phase = "relay_infra_error",
            "GET relay: infrastructure error in driver"
        );
    }

    // Release the per-tx `pending_op_results` slot at driver exit.
    // `relay_send_found` / `relay_send_not_found` / the send_to_and_await
    // in the retry loop all leave `pending_op_results[incoming_tx]`
    // populated with an is_closed sender that would only be reclaimed
    // by the 60s periodic sweep; sending `TransactionCompleted` now
    // removes the entry immediately so `test_pending_op_results_bounded`
    // stays under its leak ceiling.
    //
    // Originator-loopback exception: when this driver runs on the
    // originator's own node (`upstream_addr == own_addr`), the
    // `pending_op_results` callback for `incoming_tx` is the
    // originator's `send_and_await` waiter — NOT one this driver
    // installed. Releasing it here would emit `TransactionCompleted`
    // and remove the originator's callback BEFORE the loopback
    // `GetMsg::Response` arrives at the bypass, racing the
    // originator's wait. The originator's own driver completion
    // path (via `ClientGetCompletionGuard` →
    // `release_pending_op_slot`) cleans up the slot.
    //
    // Yield first so any in-flight `send_fire_and_forget` has time to
    // run through the event loop's `handle_op_execution` and actually
    // INSERT into `pending_op_results`. `release_pending_op_slot` uses
    // the higher-priority notification channel, so without the yield
    // the TransactionCompleted arrives before the insert and the
    // cleanup is a no-op (per the caveat in `OpCtx::send_fire_and_forget`
    // docs).
    let own_addr = op_manager.ring.connection_manager.get_own_addr();
    let originator_loopback = Some(upstream_addr) == own_addr;
    tokio::task::yield_now().await;
    if !originator_loopback {
        op_manager.release_pending_op_slot(incoming_tx).await;
    }
}

#[allow(clippy::too_many_arguments)]
async fn drive_relay_get<CB>(
    op_manager: &Arc<OpManager>,
    conn_manager: &CB,
    incoming_tx: Transaction,
    instance_id: ContractInstanceId,
    htl: usize,
    upstream_addr: SocketAddr,
    visited: VisitedPeers,
    fetch_contract: bool,
    subscribe: bool,
) -> Result<(), OpError>
where
    CB: NetworkBridge + Clone + Send + 'static,
{
    match drive_relay_get_inner(
        op_manager,
        conn_manager,
        incoming_tx,
        instance_id,
        htl,
        upstream_addr,
        visited,
        fetch_contract,
        subscribe,
    )
    .await
    {
        Ok(()) => Ok(()),
        Err(err) => {
            tracing::warn!(
                tx = %incoming_tx,
                %instance_id,
                error = %err,
                phase = "relay_inner_error",
                "GET relay: inner driver returned error; sending NotFound upstream"
            );
            // On infrastructure error, send NotFound upstream so the upstream
            // doesn't time out waiting for us.
            let hop_count = op_manager.ring.max_hops_to_live.saturating_sub(htl);
            relay_send_not_found(
                op_manager,
                incoming_tx,
                instance_id,
                upstream_addr,
                hop_count,
            )
            .await;
            Err(err)
        }
    }
}

/// Local fallback tuple: key, state, optional contract code.
type LocalFallback = (ContractKey, WrappedState, Option<ContractContainer>);

/// Relay-side local cache lookup with interest gate.
///
/// Mirrors `GetMsg::Request` match arm at `get.rs:1369-1433`.
///
/// Returns `(local_value, local_fallback)`:
/// - `local_value`: Some if we should serve immediately (active interest or
///   originator).  None if we should forward.
/// - `local_fallback`: Some if we have stale local state with no active
///   interest — used as a fallback if all downstream peers return NotFound.
async fn check_local_with_interest_gate(
    op_manager: &OpManager,
    instance_id: &ContractInstanceId,
    fetch_contract: bool,
) -> (Option<LocalFallback>, Option<LocalFallback>) {
    let get_result = op_manager
        .notify_contract_handler(ContractHandlerEvent::GetQuery {
            instance_id: *instance_id,
            return_contract_code: fetch_contract,
        })
        .await;

    let raw_local = match get_result {
        Ok(ContractHandlerEvent::GetResponse {
            key: Some(key),
            response:
                Ok(StoreResponse {
                    state: Some(state),
                    contract,
                }),
        }) => {
            if fetch_contract && contract.is_none() {
                // State available but contract code missing — cannot serve,
                // must forward to get WASM from the network.
                None
            } else {
                Some((key, state, contract))
            }
        }
        _ => None,
    };

    match raw_local {
        None => (None, None),
        Some((key, state, contract)) => {
            // Interest gate (mirrors get.rs:1408-1433):
            // Relay peers actively hosting serve immediately.
            // Peers with only stale LRU cache (no active interest) defer to
            // the network but keep the local value as fallback.
            if !op_manager.interest_manager.has_local_interest(&key) {
                // Stale cache only — defer to network, keep as fallback.
                tracing::debug!(
                    %instance_id,
                    "GET relay: stale cache (no local interest), will forward"
                );
                (None, Some((key, state, contract)))
            } else {
                // Actively hosting with interest — serve immediately.
                (Some((key, state, contract)), None)
            }
        }
    }
}

/// Select the next downstream peer for relay forwarding.
///
/// Uses `new_visited` (bloom filter) as the primary skip list for
/// `k_closest_potentially_hosting` — this already encodes the upstream's
/// skip list plus this peer and the upstream address.  `tried` is used
/// for retry-count tracking and to ensure we don't revisit peers we've
/// explicitly attempted in this driver invocation.
///
/// Returns None when exhausted (`retries >= MAX_RELAY_RETRIES`).
fn relay_advance_to_next_peer(
    op_manager: &OpManager,
    instance_id: &ContractInstanceId,
    tried: &mut Vec<SocketAddr>,
    retries: &mut usize,
    new_visited: &VisitedPeers,
) -> Option<(PeerKeyLocation, SocketAddr)> {
    // Legacy relay does NOT retry alternative peers at each hop — it
    // forwards once and bubbles back whatever downstream returned. The
    // phase-5 migration introduced a 3-peer retry loop here
    // that compounded fan-out to 3^HTL per origination under virtual
    // time (ci-fault-loss run 24602255580 showed 16.9M spawns in 95s
    // with single-use tx reuse still in place). Cap at 1 to match
    // legacy semantics exactly. If downstream fails, we bubble
    // NotFound to upstream and let the originator's client driver
    // handle cross-peer retries (which IS legitimate in
    // `drive_client_get_inner`'s retry loop).
    const MAX_RELAY_RETRIES: usize = 1;
    if *retries >= MAX_RELAY_RETRIES {
        return None;
    }
    *retries += 1;

    // Use new_visited as the skip list so upstream's visited set and our own
    // marks are both respected.
    let peer = match op_manager
        .ring
        .k_closest_potentially_hosting(instance_id, new_visited.clone(), 1)
        .into_iter()
        .next()
    {
        Some(peer) => peer,
        None => {
            // Bootstrap fallback (#4361): empty ring → forward via a
            // configured gateway instead of silently exhausting. Respects
            // both the request's visited bloom (cross-hop loop prevention —
            // a gateway the request already traversed is never re-picked)
            // and `tried` (exact local exclusion). Stays within
            // MAX_RELAY_RETRIES, so the 3^HTL fan-out guard above is
            // unaffected.
            return match bootstrap_gateway_target(op_manager, |addr| {
                tried.contains(&addr) || new_visited.probably_visited(addr)
            }) {
                Some((gw, addr)) => {
                    tracing::info!(
                        %instance_id,
                        gateway = %addr,
                        "GET relay advance: ring empty — forwarding to configured gateway"
                    );
                    tried.push(addr);
                    Some((gw, addr))
                }
                None => {
                    tracing::debug!(
                        %instance_id,
                        "GET relay advance: no routing candidates — exhausted"
                    );
                    None
                }
            };
        }
    };
    let Some(addr) = peer.socket_addr() else {
        // Rare but possible — see the matching guard in
        // `advance_to_next_peer` for why addressless candidates can leak
        // out of `k_closest_potentially_hosting`.
        tracing::warn!(
            %instance_id,
            peer = ?peer,
            "GET relay advance: selected routing candidate has no socket address — treating as exhausted"
        );
        return None;
    };
    // Double-check against tried (exact exclusion, no bloom false positives).
    if tried.contains(&addr) {
        tracing::debug!(
            %instance_id,
            peer = %addr,
            "GET relay advance: candidate already tried — exhausted"
        );
        return None;
    }
    tried.push(addr);
    Some((peer, addr))
}

/// Build and send a `GetMsg::Response{NotFound}` to `upstream_addr`.
///
/// `hop_count` is the forward-path hop count to embed in the Response. For
/// a relay that's producing the NotFound itself (HTL exhaustion or downstream
/// exhaustion), this is `max_htl - incoming_htl`. For an originator-side
/// originator-loopback NotFound from `start_client_get` after exhaustion,
/// pass 0 (no remote hops traversed).
async fn relay_send_not_found(
    op_manager: &OpManager,
    tx: Transaction,
    instance_id: ContractInstanceId,
    upstream_addr: SocketAddr,
    hop_count: usize,
) {
    let msg = NetMessage::from(GetMsg::Response {
        id: tx,
        instance_id,
        result: GetMsgResult::NotFound,
        hop_count,
    });
    let mut ctx = op_manager.op_ctx(tx);
    // Originator-loopback: when this driver runs on the originator's
    // own node (`upstream_addr == own_addr`), routing the wire-bound
    // `send_fire_and_forget(own_addr, ...)` would attempt a
    // self-connection (no peer entry exists for own_addr). Use
    // `send_local_loopback` to route as `InboundMessage` instead, so
    // the bypass at `handle_pure_network_message_v1` can forward the
    // terminal Response to the originator's `pending_op_results`
    // waiter. Mirrors `relay_put_send_response`'s loopback branch.
    let own_addr = op_manager.ring.connection_manager.get_own_addr();
    let send_result = if Some(upstream_addr) == own_addr {
        ctx.send_local_loopback(msg).await
    } else {
        ctx.send_fire_and_forget(upstream_addr, msg).await
    };
    if let Err(err) = send_result {
        tracing::warn!(
            tx = %tx,
            %instance_id,
            %upstream_addr,
            error = %err,
            "GET relay: failed to send NotFound upstream"
        );
    }
}

/// Build and send a `GetMsg::Response{Found}` (inline, non-streaming) to
/// `upstream_addr`.  Returns an error on serialization failure.
///
/// `hop_count` is the forward-path hop count to embed in the Response. For
/// the storer's own initial Found, this is `max_htl - incoming_htl`. For a
/// relay bubbling up a downstream Found, this is the downstream Response's
/// `hop_count` (preserved through the bubble-up chain).
#[allow(clippy::too_many_arguments)]
async fn relay_send_found<CB>(
    op_manager: &OpManager,
    conn_manager: &CB,
    tx: Transaction,
    instance_id: ContractInstanceId,
    upstream_addr: SocketAddr,
    key: ContractKey,
    state: WrappedState,
    contract: Option<ContractContainer>,
    hop_count: usize,
) -> Result<(), OpError>
where
    CB: NetworkBridge + Clone + Send + 'static,
{
    let mut ctx = op_manager.op_ctx(tx);
    // Originator-loopback: route via `send_local_loopback` to avoid
    // the wire-bound self-connection failure. See `relay_send_not_found`
    // for the full rationale. No streaming over loopback — there's no
    // network benefit and it avoids loopback-stream complexity.
    let own_addr = op_manager.ring.connection_manager.get_own_addr();
    if Some(upstream_addr) == own_addr {
        let msg = NetMessage::from(GetMsg::Response {
            id: tx,
            instance_id,
            result: GetMsgResult::Found {
                key,
                value: StoreResponse {
                    state: Some(state),
                    contract,
                },
            },
            hop_count,
        });
        return ctx
            .send_local_loopback(msg)
            .await
            .map_err(|_| OpError::NotificationError);
    }

    // Remote upstream: stream large payloads instead of falling back to
    // message-level store-and-forward. The legacy GET producer (#3586,
    // removed by the task-per-tx migration) did exactly this; restoring
    // it here closes #4307. Mirrors `drive_relay_put`'s streaming-upgrade
    // producer branch (put/op_ctx_task.rs).
    //
    // Capture `includes_contract` BEFORE moving `contract` into the
    // payload, since the wire header needs it but serialization consumes
    // the contract.
    let includes_contract = contract.is_some();
    let payload = GetStreamingPayload {
        key,
        value: StoreResponse {
            state: Some(state),
            contract,
        },
    };
    let payload_bytes = match bincode::serialize(&payload) {
        Ok(b) => b,
        Err(e) => {
            return Err(OpError::NotificationChannelError(format!(
                "Failed to serialize GET relay forward payload: {e}"
            )));
        }
    };

    if crate::operations::should_use_streaming(op_manager.streaming_threshold, payload_bytes.len())
    {
        let sid = StreamId::next_operations();
        tracing::info!(
            tx = %tx,
            contract = %key,
            target = %upstream_addr,
            total_size = payload_bytes.len(),
            %sid,
            phase = "relay_streaming_forward",
            "GET relay: payload exceeds threshold, streaming response upstream"
        );
        // NOTE: `hop_count` is intentionally NOT carried on the streaming
        // wire path — the `ResponseStreaming` variant has no such field
        // (unlike the inline `Response{Found}` below, which propagates
        // `hop_count`). This matches the legacy streaming producer's
        // limitation; transfer-rate routing observations on the originator
        // come from `total_size` instead, so the lost hop depth does not
        // degrade routing.
        let header = NetMessage::from(GetMsg::ResponseStreaming {
            id: tx,
            instance_id,
            stream_id: sid,
            key,
            total_size: payload_bytes.len() as u64,
            includes_contract,
        });
        // Embed a serialized copy of the metadata header in fragment #1
        // (fix #2757). On a lossy link the separately-sent fire-and-forget
        // header can be lost while fragments arrive — without self-describing
        // metadata the upstream waiter never matches the orphan stream and
        // the GET times out. Mirrors the forward path's `embedded`.
        let embedded = bincode::serialize(&header).ok().map(bytes::Bytes::from);
        if embedded.is_none() {
            tracing::warn!(
                tx = %tx,
                target = %upstream_addr,
                %sid,
                "GET relay: failed to serialize ResponseStreaming header for \
                 fragment-#1 embedding; sending stream without embedded metadata"
            );
        }
        // Install nothing — the upstream already has its waiter (it sent
        // us the Request). Send the metadata header first, then push the
        // raw fragments. Ordering matches the PUT producer.
        ctx.send_fire_and_forget(upstream_addr, header)
            .await
            .map_err(|_| OpError::NotificationError)?;
        conn_manager
            .send_stream(
                upstream_addr,
                sid,
                bytes::Bytes::from(payload_bytes),
                embedded,
            )
            .await
            .map_err(|e| {
                OpError::NotificationChannelError(format!("get relay send_stream failed: {e}"))
            })?;
        Ok(())
    } else {
        // Below threshold: inline Response{Found} (legacy behavior).
        let StoreResponse { state, contract } = payload.value;
        let msg = NetMessage::from(GetMsg::Response {
            id: tx,
            instance_id,
            result: GetMsgResult::Found {
                key,
                value: StoreResponse { state, contract },
            },
            hop_count,
        });
        ctx.send_fire_and_forget(upstream_addr, msg)
            .await
            .map_err(|_| OpError::NotificationError)
    }
}

#[allow(clippy::too_many_arguments)]
async fn drive_relay_get_inner<CB>(
    op_manager: &Arc<OpManager>,
    conn_manager: &CB,
    incoming_tx: Transaction,
    instance_id: ContractInstanceId,
    htl: usize,
    upstream_addr: SocketAddr,
    visited: VisitedPeers,
    fetch_contract: bool,
    subscribe: bool,
) -> Result<(), OpError>
where
    CB: NetworkBridge + Clone + Send + 'static,
{
    let ring_max_htl = op_manager.ring.max_hops_to_live.max(1);
    let htl = htl.min(ring_max_htl);

    // ── Short-circuit 1: HTL = 0 ────────────────────────────────────────
    if htl == 0 {
        tracing::warn!(
            tx = %incoming_tx,
            %instance_id,
            %upstream_addr,
            htl = 0,
            phase = "not_found",
            "GET relay: HTL exhausted — sending NotFound upstream"
        );
        if let Some(event) = crate::tracing::NetEventLog::get_not_found(
            &incoming_tx,
            &op_manager.ring,
            instance_id,
            Some(op_manager.ring.max_hops_to_live),
        ) {
            op_manager
                .ring
                .register_events(either::Either::Left(event))
                .await;
        }
        // HTL=0 path: the original Request reached us with htl already at 0,
        // meaning the request traversed the full max_htl forward hops to get
        // here. hop_count = max_htl - 0 = max_htl.
        let hop_count = op_manager.ring.max_hops_to_live;
        relay_send_not_found(
            op_manager,
            incoming_tx,
            instance_id,
            upstream_addr,
            hop_count,
        )
        .await;
        return Ok(());
    }

    // ── Update visited set: mark this peer and the upstream ─────────────
    let mut new_visited = visited.with_transaction(&incoming_tx);
    if let Some(own_addr) = op_manager.ring.connection_manager.get_own_addr() {
        new_visited.mark_visited(own_addr);
    }
    new_visited.mark_visited(upstream_addr);

    // ── Short-circuit 2: Local cache hit with interest ───────────────────
    let (local_value, local_fallback) =
        check_local_with_interest_gate(op_manager, &instance_id, fetch_contract).await;

    if let Some((key, state, contract)) = local_value {
        tracing::info!(
            tx = %incoming_tx,
            %instance_id,
            contract = %key,
            phase = "complete",
            "GET relay: contract found locally (active interest) — sending Found upstream"
        );

        // Register interest for the requester (mirrors get.rs:1447-1476).
        if subscribe {
            crate::operations::subscribe::register_downstream_subscriber(
                op_manager,
                &key,
                upstream_addr,
                None,
                None,
                &incoming_tx,
                " (relay loopback, piggybacked on GET)",
            )
            .await;
        } else if let Some(pkl) = op_manager
            .ring
            .connection_manager
            .get_peer_by_addr(upstream_addr)
        {
            let peer_key = crate::ring::interest::PeerKey::from(pkl.pub_key);
            let is_new = op_manager
                .interest_manager
                .register_peer_interest(&key, peer_key, None, false);
            if is_new {
                // #4359 (MUST-FIX 1): a remote GET with subscribe=false still
                // registers the requester's interest, making them a viable
                // broadcast target. Flush any deferred fresh-contract broadcast
                // so a cold-id PUT that gave up reaches this requester.
                op_manager.flush_pending_broadcast_on_interest(&key).await;
            }
        }

        // Forward upstream FIRST to keep cache work off the critical
        // path (issue #4155). `cache_contract_locally` enqueues a
        // GetQuery + PutQuery on the single-threaded `contract_handling`
        // event loop; the PutQuery runs WASM `validate_state` (and may
        // recursively `RequestRelated` with a 10s
        // `RELATED_FETCH_TIMEOUT`). When that queue is backed up,
        // per-hop dwell can reach many seconds. Forwarding first drops
        // the upstream-visible per-hop dwell from O(validate_state) to
        // O(channel_send).
        //
        // Caching ALWAYS runs after forwarding, even when forwarding
        // returns Err — this preserves the legacy invariant that LRU/TTL
        // bookkeeping and `announce_contract_hosted` fire on any successful
        // wire-level GET. The send error is deferred via `let send_result`
        // and propagated after the cache call.
        //
        // R4 (this site) and R10 read from the local store, so the
        // `state_matches` short-circuit inside `cache_contract_locally`
        // skips the expensive PutQuery — the perf win is concentrated
        // at R12a (downstream-Found bubble-up). We still reorder R4/R10
        // uniformly so the invariant "forward before cache" holds across
        // every relay-driver callsite and a future refactor can't
        // accidentally re-introduce cache-before-forward at any one site.
        //
        // The forwarded bytes get re-validated at the next hop /
        // originator, so the relay doesn't need to validate locally to
        // forward safely. `is_client_requester=false` on the cache
        // call: relay peers must not set the sticky
        // `local_client_access` flag — that's exclusively for the
        // client-originating node. Legacy mirror: `get.rs:2260-2262`
        // gates on `is_original_requester`.
        // R4 (local cache hit): this relay IS the storer. hop_count =
        // max_htl - htl_we_received.
        let hop_count = op_manager.ring.max_hops_to_live.saturating_sub(htl);
        let send_result = relay_send_found(
            op_manager,
            conn_manager,
            incoming_tx,
            instance_id,
            upstream_addr,
            key,
            state.clone(),
            contract.clone(),
            hop_count,
        )
        .await;
        cache_contract_locally(op_manager, key, state, contract, false).await;
        send_result?;
        return Ok(());
    }

    // ── Retry loop: forward to downstream peers ──────────────────────────
    // `tried` tracks the exact addrs we've attempted for retry counting.
    // The bloom filter `new_visited` acts as the skip list for
    // `k_closest_potentially_hosting` (it already has own_addr and
    // upstream_addr marked in).
    let mut tried: Vec<SocketAddr> = Vec::new();
    if let Some(own_addr) = op_manager.ring.connection_manager.get_own_addr() {
        tried.push(own_addr);
    }
    tried.push(upstream_addr);

    let mut retries: usize = 0;

    loop {
        // Pick next downstream peer.
        let (peer, peer_addr) = match relay_advance_to_next_peer(
            op_manager,
            &instance_id,
            &mut tried,
            &mut retries,
            &new_visited,
        ) {
            Some(p) => p,
            None => {
                // Exhausted: serve local fallback if available, else NotFound.
                if let Some((key, state, contract)) = local_fallback {
                    tracing::info!(
                        tx = %incoming_tx,
                        %instance_id,
                        contract = %key,
                        "GET relay: all peers exhausted — serving local fallback"
                    );
                    // Forward upstream FIRST to keep cache off the critical
                    // path (issue #4155 — see top-of-loop comment above the
                    // R4 callsite for the full rationale). Cache ALWAYS
                    // runs after forwarding so LRU/TTL bookkeeping fires
                    // even when the forward errors. Relay path:
                    // `is_client_requester=false` on the cache call.
                    // R10 (local fallback): this relay is acting as the
                    // storer; same hop_count semantics as R4.
                    let hop_count = op_manager.ring.max_hops_to_live.saturating_sub(htl);
                    let send_result = relay_send_found(
                        op_manager,
                        conn_manager,
                        incoming_tx,
                        instance_id,
                        upstream_addr,
                        key,
                        state.clone(),
                        contract.clone(),
                        hop_count,
                    )
                    .await;
                    cache_contract_locally(op_manager, key, state, contract, false).await;
                    send_result?;
                } else {
                    tracing::warn!(
                        tx = %incoming_tx,
                        %instance_id,
                        %upstream_addr,
                        phase = "not_found",
                        "GET relay: all peers exhausted — sending NotFound upstream"
                    );
                    // Exhaustion NotFound: this relay is reporting its own
                    // exhaustion of downstream candidates. hop_count is its
                    // forward depth (max_htl - htl).
                    let hop_count = op_manager.ring.max_hops_to_live.saturating_sub(htl);
                    if let Some(event) = crate::tracing::NetEventLog::get_not_found(
                        &incoming_tx,
                        &op_manager.ring,
                        instance_id,
                        Some(hop_count),
                    ) {
                        op_manager
                            .ring
                            .register_events(either::Either::Left(event))
                            .await;
                    }
                    relay_send_not_found(
                        op_manager,
                        incoming_tx,
                        instance_id,
                        upstream_addr,
                        hop_count,
                    )
                    .await;
                }
                return Ok(());
            }
        };

        // NOTE: legacy path sends a ForwardingAck upstream before forwarding
        // downstream so the upstream's GC can extend its timer on slow
        // multi-hop chains. In the driver relay driver we OMIT that
        // ack: the ack carried `incoming_tx` (which equals the upstream's
        // `attempt_tx` on a relay-to-relay hop), so it matched the
        // upstream's capacity-1 `pending_op_results` waiter and arrived
        // FIRST, before the real Response. `classify` returned
        // `Unexpected`, causing upstream to abandon the downstream probe
        // and spawn a new attempt. That amplified to 3^HTL spawns per
        // origination under ci-fault-loss, driving the 63GB RSS explosion
        // (workflow runs 24600168871 / 24600634908 / 24601267577).
        //
        // Upstream's `send_to_and_await` still has its full OPERATION_TTL
        // (60s) to receive the real Response, which is the same timeout
        // legacy had minus the ack-driven extension. That extension is
        // only observable under chains longer than 60s wall-clock, which
        // `min_success_rate=0.80` tolerates at ci-fault-loss parameters.

        tracing::debug!(
            tx = %incoming_tx,
            %instance_id,
            target = %peer,
            target_addr = %peer_addr,
            phase = "forward",
            "GET relay: forwarding request to downstream peer"
        );

        // Emit get_request telemetry for the relay forward.
        let new_htl = htl.saturating_sub(1);
        if let Some(event) = crate::tracing::NetEventLog::get_request(
            &incoming_tx,
            &op_manager.ring,
            instance_id,
            peer.clone(),
            new_htl,
        ) {
            op_manager
                .ring
                .register_events(either::Either::Left(event))
                .await;
        }

        // Forward downstream using the INCOMING tx (end-to-end preservation,
        // matching legacy relay semantics). Minting a fresh `attempt_tx`
        // per retry was the 3^HTL amplifier: downstream peers saw every
        // retry as a brand-new Request, spawned a fresh relay subtree,
        // and the aggregate spawn rate reached 7M/100s in ci-fault-loss
        // (workflow run 24601908758). Reusing `incoming_tx` keeps the
        // pending_op_results callback bound to a single key per hop;
        // retries re-register the same callback after the previous
        // attempt's receiver was consumed by timeout or reply.
        let request = NetMessage::from(GetMsg::Request {
            id: incoming_tx,
            instance_id,
            fetch_contract,
            htl: new_htl,
            visited: new_visited.clone(),
            subscribe,
        });

        // Originator-loopback: when the relay driver runs on the
        // originator's own node, `incoming_tx == client_tx`. Calling
        // `send_to_and_await(peer_addr, ...)` would install a NEW
        // `pending_op_results[client_tx]` callback OVERWRITING the
        // originator's `start_client_get` waiter (`handle_op_execution`
        // calls `state.pending_op_results.insert(...)` which overwrites).
        // The peer's downstream Response would then land in the
        // relay-driver's callback and never reach the client driver.
        //
        // Fix: in originator-loopback, fire-and-forget the downstream
        // Request and exit without awaiting — `send_fire_and_forget`
        // dispatches a callback whose receiver is dropped, so
        // `handle_op_execution` skips the insert (closed-callback
        // guard at p2p_protoc.rs). The peer's eventual Response
        // returns over the wire, and the bypass at
        // `handle_pure_network_message_v1` forwards it to the
        // originator's still-installed callback. The client driver
        // owns retry semantics; the relay driver has nothing to add.
        // Mirrors `drive_relay_put`'s originator-loopback branch.
        let own_addr = op_manager.ring.connection_manager.get_own_addr();
        let originator_loopback = Some(upstream_addr) == own_addr;
        let mut ctx = op_manager.op_ctx(incoming_tx);
        if originator_loopback {
            if let Err(err) = ctx.send_fire_and_forget(peer_addr, request).await {
                tracing::warn!(
                    tx = %incoming_tx,
                    target = %peer,
                    error = %err,
                    "GET relay (loopback, loopback): \
                     send_fire_and_forget failed"
                );
                // Fall through to NotFound — client driver waiter
                // owns the retry decision.
                return Err(err);
            }
            // Exit driver: client driver owns the response handling.
            return Ok(());
        }

        let round_trip =
            tokio::time::timeout(OPERATION_TTL, ctx.send_to_and_await(peer_addr, request)).await;

        // Always release the slot so the next retry can re-register.
        op_manager.release_pending_op_slot(incoming_tx).await;

        let reply = match round_trip {
            Ok(Ok(reply)) => reply,
            Ok(Err(err)) => {
                tracing::warn!(
                    tx = %incoming_tx,
                    target = %peer,
                    error = %err,
                    "GET relay: send_to_and_await failed; advancing to next peer"
                );
                // Feed the relay's failed peer choice into the local Router
                // so future routing decisions de-prioritize this peer. Without
                // this hook, only originator-side failures train the router
                // and per-peer dashboard panels stay empty on relay-heavy nodes.
                crate::operations::record_relay_route_event(
                    op_manager,
                    peer.clone(),
                    crate::ring::Location::from(&instance_id),
                    crate::router::RouteOutcome::Failure,
                    crate::node::network_status::OpType::Get,
                );
                // Continue loop to try next peer.
                new_visited.mark_visited(peer_addr);
                continue;
            }
            Err(_elapsed) => {
                tracing::warn!(
                    tx = %incoming_tx,
                    target = %peer,
                    timeout_secs = OPERATION_TTL.as_secs(),
                    "GET relay: attempt timed out; advancing to next peer"
                );
                crate::operations::record_relay_route_event(
                    op_manager,
                    peer.clone(),
                    crate::ring::Location::from(&instance_id),
                    crate::router::RouteOutcome::Failure,
                    crate::node::network_status::OpType::Get,
                );
                new_visited.mark_visited(peer_addr);
                continue;
            }
        };

        // Classify the reply.
        match classify(reply) {
            AttemptOutcome::Terminal(Terminal::InlineFound {
                key,
                state,
                contract,
                hop_count: downstream_hop_count,
            }) => {
                tracing::info!(
                    tx = %incoming_tx,
                    %instance_id,
                    contract = %key,
                    phase = "relay_found",
                    "GET relay: downstream returned Found — forwarding upstream then caching locally"
                );

                // Feed the relay's successful peer choice into the local
                // Router. Without this hook, only originator-side successes
                // train the failure-probability model and per-peer dashboard
                // panels stay empty on relay-heavy nodes. In-memory only,
                // safe to run before forwarding.
                crate::operations::record_relay_route_event(
                    op_manager,
                    peer.clone(),
                    crate::ring::Location::from(&instance_id),
                    crate::router::RouteOutcome::SuccessUntimed,
                    crate::node::network_status::OpType::Get,
                );

                // Bubble up to upstream FIRST to keep cache off the
                // critical path (issue #4155 — full rationale at the
                // R4 callsite earlier in this fn). This is THE site
                // where the perf win matters: a freshly-arrived
                // downstream payload has no `state_matches`
                // short-circuit yet, so the PutQuery runs full WASM
                // `validate_state` + `update_state`. Caching ALWAYS
                // runs after forwarding so LRU/TTL and
                // `announce_contract_hosted` semantics are preserved
                // even on send error.
                // Preserve the storer-side hop_count so the originator
                // sees the *forward* depth from Request to storer, not
                // the depth from Request to this relay.
                let send_result = relay_send_found(
                    op_manager,
                    conn_manager,
                    incoming_tx,
                    instance_id,
                    upstream_addr,
                    key,
                    state.clone(),
                    contract.clone(),
                    downstream_hop_count,
                )
                .await;

                // Cache locally (relay opportunistically caches forwarded
                // Found payloads). `is_client_requester=false` so this node
                // does NOT set `mark_local_client_access` — the sticky flag
                // belongs to the upstream client-originating node, not a
                // forwarder. `announce_contract_hosted` DOES fire when
                // `access_result.is_new && put_persisted` so first-time
                // hosting at a relay is still broadcast (matches legacy
                // `get.rs:2370` which announces on any first-time relay
                // cache).
                cache_contract_locally(op_manager, key, state, contract, false).await;
                send_result?;
                return Ok(());
            }
            AttemptOutcome::Terminal(Terminal::Streaming {
                key,
                stream_id,
                includes_contract,
                total_size,
            }) => {
                // Downstream answered with a streaming response. Restore the
                // relay fork+pipe forward (reverted #3586 / port plan §7,
                // issue #4307): claim the inbound stream, fork it, send the
                // metadata header upstream, then pipe fragments onward. The
                // relay caches a best-effort local copy from the held handle
                // AFTER initiating the pipe. Mirrors
                // `drive_relay_put_streaming`.
                let own_addr = op_manager.ring.connection_manager.get_own_addr();

                tracing::info!(
                    tx = %incoming_tx,
                    %instance_id,
                    contract = %key,
                    target = %peer,
                    %stream_id,
                    total_size,
                    phase = "relay_streaming_forward",
                    "GET relay: downstream returned ResponseStreaming — forwarding stream upstream"
                );

                // ── Step 1: Claim the inbound stream (atomic dedup). The
                //    DOWNSTREAM peer (`peer_addr`) is the responder.
                let handle = match op_manager
                    .orphan_stream_registry()
                    .claim_or_wait(peer_addr, stream_id, STREAM_CLAIM_TIMEOUT)
                    .await
                {
                    Ok(h) => h,
                    Err(OrphanStreamError::AlreadyClaimed) => {
                        // Dedup, NOT a routing failure: another task already
                        // owns this stream. Do NOT record a Failure route
                        // event here — the downstream peer behaved correctly.
                        tracing::debug!(
                            tx = %incoming_tx,
                            %stream_id,
                            "GET relay: inbound stream already claimed (dedup), skipping"
                        );
                        return Ok(());
                    }
                    Err(e) => {
                        tracing::warn!(
                            tx = %incoming_tx,
                            %stream_id,
                            target = %peer,
                            error = %e,
                            "GET relay: orphan stream claim failed; advancing to next peer"
                        );
                        // The downstream advertised a `ResponseStreaming`
                        // header but never delivered an assemblable stream
                        // (timeout / claim error) — a genuine routing failure
                        // for this peer. Train the router the same way the
                        // transport-failure arms above do, so a peer that
                        // stalls on stream delivery gets de-prioritised
                        // instead of being re-selected. (AlreadyClaimed above
                        // is deliberately NOT counted — that's dedup, not a
                        // failure.)
                        crate::operations::record_relay_route_event(
                            op_manager,
                            peer.clone(),
                            crate::ring::Location::from(&instance_id),
                            crate::router::RouteOutcome::Failure,
                            crate::node::network_status::OpType::Get,
                        );
                        // Treat as a failed attempt — try another peer.
                        new_visited.mark_visited(peer_addr);
                        continue;
                    }
                };

                // ── Step 2: Loopback safety net. If upstream IS us
                //    (originator-loopback edge — rare), assemble + cache
                //    locally instead of piping to self. This branch is
                //    cache-only with NO wire Response: relay-loopback
                //    initiators (GC-spawned retries / start_targeted_op
                //    auto-fetch) only need the local cache populated — the
                //    interactive client GET uses the separate
                //    `drive_client_get_inner` driver, which owns its own
                //    client delivery.
                if Some(upstream_addr) == own_addr {
                    match handle.assemble().await {
                        Ok(bytes) => match bincode::deserialize::<GetStreamingPayload>(&bytes) {
                            Ok(payload) => {
                                if let Some(state) = payload.value.state {
                                    let contract = if includes_contract {
                                        payload.value.contract
                                    } else {
                                        None
                                    };
                                    cache_contract_locally(
                                        op_manager,
                                        payload.key,
                                        state,
                                        contract,
                                        false,
                                    )
                                    .await;
                                } else {
                                    tracing::warn!(
                                        tx = %incoming_tx,
                                        %stream_id,
                                        "GET relay (loopback): streamed payload has no state"
                                    );
                                }
                            }
                            Err(e) => {
                                tracing::warn!(
                                    tx = %incoming_tx,
                                    %stream_id,
                                    error = %e,
                                    "GET relay (loopback): failed to deserialize streamed payload"
                                );
                            }
                        },
                        Err(e) => {
                            tracing::warn!(
                                tx = %incoming_tx,
                                %stream_id,
                                error = %e,
                                "GET relay (loopback): stream assembly failed"
                            );
                        }
                    }
                    return Ok(());
                }

                // ── Step 3: Forward path (remote upstream). Fork, send
                //    metadata header, pipe — BEFORE any local assemble/cache.
                //    Re-key with a FRESH outbound stream_id per hop.
                let outbound_sid = StreamId::next_operations();
                let forked = handle.fork();
                let header = GetMsg::ResponseStreaming {
                    id: incoming_tx,
                    instance_id,
                    stream_id: outbound_sid,
                    key,
                    total_size,
                    includes_contract,
                };
                let header_net = NetMessage::from(header);
                // Serialize metadata for embedding in fragment #1 (fix #2757).
                let embedded = bincode::serialize(&header_net).ok().map(bytes::Bytes::from);

                // Committed to forking + piping to a remote upstream: count
                // this streaming-forward hop (test-only; see counter doc).
                #[cfg(any(test, feature = "testing"))]
                RELAY_GET_STREAMING_FORWARD_COUNT.fetch_add(1, std::sync::atomic::Ordering::SeqCst);

                // Send the metadata header BEFORE piping. The upstream
                // already has its waiter installed (it sent us the Request),
                // so a fire-and-forget header suffices.
                op_manager
                    .op_ctx(incoming_tx)
                    .send_fire_and_forget(upstream_addr, header_net)
                    .await
                    .map_err(|_| OpError::NotificationError)?;

                // `pipe_stream` spawns a background task and returns
                // promptly, so this does not block on the full transfer.
                //
                // Do NOT `?` this error: the `ResponseStreaming` header has
                // already gone upstream (see send above), so the upstream is
                // committed to assembling a stream. Propagating the error
                // would bubble up to `drive_relay_get`, which sends a
                // compensating `Response{NotFound}` to the SAME upstream — a
                // contradictory double-signal that stalls the upstream ~60s
                // on `claim_or_wait`. Instead, log and return cleanly so the
                // upstream's claim simply times out without a NotFound. We do
                // NOT fall through to the local-cache step: the held `handle`
                // may be partial after a pipe failure.
                if let Err(e) = conn_manager
                    .pipe_stream(upstream_addr, outbound_sid, forked, embedded)
                    .await
                {
                    tracing::warn!(
                        tx = %incoming_tx,
                        %upstream_addr,
                        %outbound_sid,
                        error = %e,
                        "GET relay: pipe_stream failed AFTER the ResponseStreaming \
                         header already went upstream; letting the upstream's claim \
                         time out cleanly rather than sending a contradictory NotFound"
                    );
                    return Ok(());
                }

                // ── Step 4: Record the relay route event for the downstream
                //    peer that served the stream (it behaved correctly).
                crate::operations::record_relay_route_event(
                    op_manager,
                    peer.clone(),
                    crate::ring::Location::from(&instance_id),
                    crate::router::RouteOutcome::SuccessUntimed,
                    crate::node::network_status::OpType::Get,
                );

                // ── Step 5: Subscriber-forwarding parity (subscribe only).
                if subscribe {
                    crate::operations::subscribe::register_downstream_subscriber(
                        op_manager,
                        &key,
                        upstream_addr,
                        None,
                        None,
                        &incoming_tx,
                        " (relay, streamed GET response)",
                    )
                    .await;
                }

                // ── Step 6: Best-effort local cache (legacy parity — relays
                //    cache forwarded payloads). `fork()` SHARES the buffer,
                //    so the held `handle` can still assemble. On error, log
                //    and continue — the pipe already succeeded.
                match handle.assemble().await {
                    Ok(bytes) => match bincode::deserialize::<GetStreamingPayload>(&bytes) {
                        Ok(payload) => {
                            if let Some(state) = payload.value.state {
                                let contract = if includes_contract {
                                    payload.value.contract
                                } else {
                                    None
                                };
                                cache_contract_locally(
                                    op_manager,
                                    payload.key,
                                    state,
                                    contract,
                                    false,
                                )
                                .await;
                            } else {
                                tracing::warn!(
                                    tx = %incoming_tx,
                                    %stream_id,
                                    "GET relay: streamed payload has no state; skipping local cache"
                                );
                            }
                        }
                        Err(e) => {
                            tracing::warn!(
                                tx = %incoming_tx,
                                %stream_id,
                                error = %e,
                                "GET relay: failed to deserialize streamed payload for local cache"
                            );
                        }
                    },
                    Err(e) => {
                        tracing::warn!(
                            tx = %incoming_tx,
                            %stream_id,
                            error = %e,
                            "GET relay: stream assembly failed for local cache (pipe already sent)"
                        );
                    }
                }

                return Ok(());
            }
            AttemptOutcome::Terminal(Terminal::LocalCompletion) => {
                // A relay driver should never receive a Request-echo because
                // `send_to_and_await` targets a specific remote peer (not
                // loopback). If this arrives, it is a local protocol bug —
                // not a peer-routing failure. Do NOT record a route event.
                tracing::warn!(
                    tx = %incoming_tx,
                    %instance_id,
                    "GET relay: unexpected LocalCompletion (Request-echo) — trying next peer"
                );
                new_visited.mark_visited(peer_addr);
                continue;
            }
            AttemptOutcome::Retry => {
                // Downstream peer correctly answered NotFound. The peer
                // behaved well at the protocol level — it just doesn't host
                // this contract. Record `SuccessUntimed`: the failure-
                // probability model should treat this peer as healthy, even
                // though the relay tries another candidate for *this*
                // contract location.
                tracing::debug!(
                    tx = %incoming_tx,
                    target = %peer,
                    "GET relay: downstream returned NotFound; advancing to next peer"
                );
                crate::operations::record_relay_route_event(
                    op_manager,
                    peer.clone(),
                    crate::ring::Location::from(&instance_id),
                    crate::router::RouteOutcome::SuccessUntimed,
                    crate::node::network_status::OpType::Get,
                );
                // Mark the failed peer so future iterations don't re-select it.
                new_visited.mark_visited(peer_addr);
                // Loop iterates to next peer.
                continue;
            }
            AttemptOutcome::Unexpected => {
                // Unexpected reply variant — could be a local bug or a peer
                // misbehaviour. Without knowing which, do NOT record a route
                // event; the helper's invariant is one event per
                // unambiguously-attributable observation.
                tracing::warn!(
                    tx = %incoming_tx,
                    target = %peer,
                    "GET relay: unexpected reply variant; advancing to next peer"
                );
                new_visited.mark_visited(peer_addr);
                continue;
            }
        }
    }
}

// ── End of relay GET driver ──────────────────────────────────────────────────

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

    fn dummy_key() -> ContractKey {
        ContractKey::from_id_and_code(ContractInstanceId::new([1u8; 32]), CodeHash::new([2u8; 32]))
    }

    fn dummy_tx() -> Transaction {
        Transaction::new::<GetMsg>()
    }

    /// `start_client_get` must acquire a `ClientOpGuard` before the
    /// `GlobalExecutor::spawn` and move it into the spawned future.
    /// See the sibling pin in `put/op_ctx_task.rs` for the full
    /// rationale (shutdown drain depends on the per-driver counter).
    #[test]
    fn start_client_get_acquires_inflight_guard_before_spawn() {
        let src = include_str!("op_ctx_task.rs");
        let entry = src
            .find("pub(crate) async fn start_client_get(")
            .expect("start_client_get must exist");
        let after_spawn = src[entry..]
            .find("GlobalExecutor::spawn(")
            .expect("start_client_get must spawn a driver task");
        let before_spawn = &src[entry..entry + after_spawn];
        assert!(
            before_spawn.contains("op_manager.admit_client_op()"),
            "start_client_get must call op_manager.admit_client_op() \
             before GlobalExecutor::spawn (atomic admission gate + \
             counter bump; closes the Codex r2 TOCTOU)."
        );
        assert!(
            before_spawn.contains("OpError::NodeShuttingDown"),
            "start_client_get must early-return OpError::NodeShuttingDown \
             on a refused admission."
        );
        let spawned = &src[entry + after_spawn..];
        let block_end = spawned
            .find("\n    Ok(client_tx)")
            .expect("start_client_get must return Ok(client_tx)");
        let spawn_block = &spawned[..block_end];
        assert!(
            spawn_block.contains("let _inflight_guard = inflight_guard;"),
            "the ClientOpGuard must be moved into the spawned future \
             via `let _inflight_guard = inflight_guard;`."
        );
    }

    /// Phase 7 egress self-block pin (#4300). `start_client_get` MUST
    /// reject a banned contract BEFORE spawning the driver task. Mirrors
    /// the receive-side `get_dispatch_gates_banned_contracts` pin in
    /// `ring/contract_ban_list.rs`. See the sibling pin in
    /// `put/op_ctx_task.rs` for the full rationale.
    #[test]
    fn start_client_get_gates_banned_contracts_before_spawn() {
        let src = include_str!("op_ctx_task.rs");
        let entry = src
            .find("pub(crate) async fn start_client_get(")
            .expect("start_client_get must exist");
        let after_spawn = src[entry..]
            .find("GlobalExecutor::spawn(")
            .expect("start_client_get must spawn a driver task");
        let before_spawn = &src[entry..entry + after_spawn];
        assert!(
            before_spawn.contains("reject_if_contract_banned"),
            "start_client_get must call reject_if_contract_banned() \
             before GlobalExecutor::spawn so a banned contract's GET is \
             rejected with a typed error instead of being driven to peers \
             (#4300 egress self-block)."
        );
    }

    // --- Bootstrap gateway fallback (#4361) ---

    fn gw(port: u16) -> PeerKeyLocation {
        let key = crate::transport::TransportPublicKey::from_bytes([port as u8; 32]);
        let addr = SocketAddr::from(([127, 0, 0, 1], port));
        PeerKeyLocation::new(key, addr)
    }

    /// Regression for #4361: a node with an empty ring but configured
    /// gateways must select a gateway instead of exhausting. Before the
    /// fix, every GET on a freshly-bootstrapped node returned NotFound
    /// without sending a single wire message.
    #[test]
    fn bootstrap_fallback_selects_gateway_when_ring_empty() {
        let gateway = gw(4001);
        let selected = select_bootstrap_gateway(0, std::slice::from_ref(&gateway), None, |_| false);
        let (peer, addr) = selected.expect("empty ring + configured gateway must select it");
        assert_eq!(peer.socket_addr(), gateway.socket_addr());
        assert_eq!(addr, gateway.socket_addr().unwrap());
    }

    /// The fallback must stay out of the way when the ring has ANY
    /// connections — a non-empty ring means normal routing had its
    /// chance and exhaustion is genuine.
    #[test]
    fn bootstrap_fallback_inactive_when_ring_non_empty() {
        let gateway = gw(4001);
        assert!(
            select_bootstrap_gateway(1, &[gateway], None, |_| false).is_none(),
            "fallback must not fire with ring connections present"
        );
    }

    /// A gateway node must never select itself (self-loop guard), but
    /// must still be able to fall back to OTHER configured gateways.
    #[test]
    fn bootstrap_fallback_skips_self() {
        let gw1 = gw(4001);
        let gw2 = gw(4002);
        let own_addr = gw1.socket_addr();
        let selected =
            select_bootstrap_gateway(0, &[gw1.clone(), gw2.clone()], own_addr, |_| false);
        let (peer, _) = selected.expect("second gateway should be selected");
        assert_eq!(
            peer.socket_addr(),
            gw2.socket_addr(),
            "self gateway must be skipped"
        );
        assert!(
            select_bootstrap_gateway(0, std::slice::from_ref(&gw1), gw1.socket_addr(), |_| false)
                .is_none(),
            "sole self gateway must yield no fallback"
        );
    }

    /// Already-tried/visited gateways are excluded, so retries cannot
    /// loop on the same gateway and a request that already traversed a
    /// gateway is never bounced back to it.
    #[test]
    fn bootstrap_fallback_excludes_tried_gateways() {
        let gw1 = gw(4001);
        let gw2 = gw(4002);
        let tried = [gw1.socket_addr().unwrap()];
        let selected = select_bootstrap_gateway(0, &[gw1.clone(), gw2.clone()], None, |addr| {
            tried.contains(&addr)
        });
        let (peer, _) = selected.expect("untried gateway should be selected");
        assert_eq!(peer.socket_addr(), gw2.socket_addr());
        let all_tried = [gw1.socket_addr().unwrap(), gw2.socket_addr().unwrap()];
        assert!(
            select_bootstrap_gateway(0, &[gw1, gw2], None, |addr| all_tried.contains(&addr))
                .is_none(),
            "all gateways tried must yield no fallback"
        );
    }

    /// Source pin (#4361): the GET peer-selection sites — client
    /// initial pick, sub-op initial pick, client advance, relay advance —
    /// must all consult `bootstrap_gateway_target` when
    /// `k_closest_potentially_hosting` yields nothing. A refactor that
    /// drops any of these calls silently reintroduces the empty-ring
    /// instant-NotFound bug. Uses `extract_fn_body` (brace-matched) so
    /// the pins cannot false-pass on neighboring code or false-fail on
    /// comment growth.
    #[test]
    fn all_selection_sites_use_bootstrap_gateway_fallback() {
        let src = production_source();

        for entry in [
            "async fn drive_client_get_inner",
            "async fn drive_sub_op_get",
            "fn advance_to_next_peer",
            "fn relay_advance_to_next_peer",
        ] {
            let body = extract_fn_body(src, entry);
            assert!(
                body.contains("bootstrap_gateway_target("),
                "{entry} must consult bootstrap_gateway_target when \
                 k_closest_potentially_hosting yields no candidates (#4361)"
            );
        }

        // The relay fallback's exclusion predicate must respect the
        // request's visited bloom — dropping the `probably_visited` half
        // would silently reintroduce gateway<->relay bounce (cross-hop
        // loop prevention; testing review of #4364).
        let relay_body = extract_fn_body(src, "fn relay_advance_to_next_peer");
        assert!(
            relay_body.contains("new_visited.probably_visited"),
            "relay_advance_to_next_peer's fallback exclusion must include \
             new_visited.probably_visited (#4361 cross-hop loop prevention)"
        );

        // The client driver must carry its tried set into each new
        // attempt's visited bloom — without it the per-attempt loopback
        // relay re-picks the same first gateway and multi-gateway
        // failover never reaches the wire (skeptical review H1 on
        // #4364). The carry's exclusion semantics are behaviorally
        // pinned by the `carry_tried_into_visited_*` tests below.
        let nat_body = extract_fn_body(src, "fn new_attempt_tx");
        assert!(
            nat_body.contains("carry_tried_into_visited("),
            "GetRetryDriver::new_attempt_tx must carry tried addrs into \
             the fresh attempt_visited bloom so gateway failover reaches \
             the wire (#4361 / #4364 H1)"
        );
        assert!(
            nat_body.contains("connection_count()"),
            "the failover carry must stay gated on the empty-ring case so \
             normal-path retry routing semantics are unchanged (#4364)"
        );
    }

    /// Behavioral pin for the failover carry (#4364 H1): previously
    /// tried addrs must be excluded from the next attempt, while the
    /// attempt's intended destination must NOT be — marking it would
    /// make the loopback relay skip the client's own pick, and
    /// single-gateway retries would exhaust instantly.
    #[test]
    fn carry_tried_into_visited_excludes_current_target() {
        let tx = dummy_tx();
        let mut visited = VisitedPeers::new(&tx);
        let own = SocketAddr::from(([127, 0, 0, 1], 4000));
        let gw1 = SocketAddr::from(([127, 0, 0, 1], 4001));
        let gw2 = SocketAddr::from(([127, 0, 0, 1], 4002));

        carry_tried_into_visited(&mut visited, &[own, gw1, gw2], Some(gw2));

        assert!(
            visited.probably_visited(own),
            "own addr must be carried into the bloom"
        );
        assert!(
            visited.probably_visited(gw1),
            "a previously tried gateway must be excluded from the next attempt"
        );
        assert!(
            !visited.probably_visited(gw2),
            "the attempt's intended destination must NOT be excluded"
        );
    }

    /// With no current target (genuinely isolated retry), everything
    /// tried is carried.
    #[test]
    fn carry_tried_into_visited_marks_all_without_current_target() {
        let tx = dummy_tx();
        let mut visited = VisitedPeers::new(&tx);
        let own = SocketAddr::from(([127, 0, 0, 1], 4000));

        carry_tried_into_visited(&mut visited, &[own], None);

        assert!(visited.probably_visited(own));
    }

    #[test]
    fn classify_response_found_is_inline_terminal() {
        let tx = dummy_tx();
        let key = dummy_key();
        let msg = NetMessage::V1(NetMessageV1::Get(GetMsg::Response {
            id: tx,
            instance_id: *key.id(),
            result: GetMsgResult::Found {
                key,
                value: StoreResponse {
                    state: Some(WrappedState::new(vec![1u8])),
                    contract: None,
                },
            },
            hop_count: 0,
        }));
        assert!(matches!(
            classify(msg),
            AttemptOutcome::Terminal(Terminal::InlineFound { .. })
        ));
    }

    /// Regression pin: `classify` MUST extract the wire-carried hop_count
    /// from `Response{Found}` and propagate it into `Terminal::InlineFound`
    /// unchanged.  The relay bubble-up at line 2355 uses this field as the
    /// hop_count for the upstream Response; a regression that synthesised 0
    /// here (or dropped the field) would silently collapse the storer's
    /// forward-path depth at every relay, defeating the whole PR.  The
    /// bincode-roundtrip unit test in `get.rs` catches the wire format only.
    /// This pins the classifier side.
    #[test]
    fn classify_response_found_preserves_hop_count() {
        for hc in [0_usize, 1, 4, 10, 64] {
            let tx = dummy_tx();
            let key = dummy_key();
            let msg = NetMessage::V1(NetMessageV1::Get(GetMsg::Response {
                id: tx,
                instance_id: *key.id(),
                result: GetMsgResult::Found {
                    key,
                    value: StoreResponse {
                        state: Some(WrappedState::new(vec![1u8])),
                        contract: None,
                    },
                },
                hop_count: hc,
            }));
            match classify(msg) {
                AttemptOutcome::Terminal(Terminal::InlineFound { hop_count, .. }) => {
                    assert_eq!(
                        hop_count, hc,
                        "classifier must preserve hop_count={hc} unchanged"
                    );
                }
                AttemptOutcome::Terminal(_)
                | AttemptOutcome::Retry
                | AttemptOutcome::Unexpected => {
                    panic!("expected Terminal(InlineFound) for hop_count={hc}");
                }
            }
        }
    }

    #[test]
    fn classify_response_notfound_is_retry() {
        let tx = dummy_tx();
        let key = dummy_key();
        let msg = NetMessage::V1(NetMessageV1::Get(GetMsg::Response {
            id: tx,
            instance_id: *key.id(),
            result: GetMsgResult::NotFound,
            hop_count: 0,
        }));
        assert!(matches!(classify(msg), AttemptOutcome::Retry));
    }

    #[test]
    fn classify_response_streaming_is_streaming_terminal() {
        let tx = dummy_tx();
        let key = dummy_key();
        let msg = NetMessage::V1(NetMessageV1::Get(GetMsg::ResponseStreaming {
            id: tx,
            instance_id: *key.id(),
            stream_id: crate::transport::peer_connection::StreamId::next(),
            key,
            total_size: 1024,
            includes_contract: true,
        }));
        assert!(matches!(
            classify(msg),
            AttemptOutcome::Terminal(Terminal::Streaming { .. })
        ));
    }

    #[test]
    fn classify_forwarding_ack_is_unexpected() {
        let tx = dummy_tx();
        let key = dummy_key();
        let msg = NetMessage::V1(NetMessageV1::Get(GetMsg::ForwardingAck {
            id: tx,
            instance_id: *key.id(),
        }));
        assert!(
            matches!(classify(msg), AttemptOutcome::Unexpected),
            "ForwardingAck must NOT be classified as terminal"
        );
    }

    #[test]
    fn classify_response_streaming_ack_is_unexpected() {
        let tx = dummy_tx();
        let msg = NetMessage::V1(NetMessageV1::Get(GetMsg::ResponseStreamingAck {
            id: tx,
            stream_id: crate::transport::peer_connection::StreamId::next(),
        }));
        assert!(matches!(classify(msg), AttemptOutcome::Unexpected));
    }

    #[test]
    fn classify_request_echo_is_local_completion() {
        // When process_message completes locally (no next hop, contract
        // already cached), the Request is echoed back via
        // forward_pending_op_result_if_completed.
        let tx = dummy_tx();
        let key = dummy_key();
        let msg = NetMessage::V1(NetMessageV1::Get(GetMsg::Request {
            id: tx,
            instance_id: *key.id(),
            fetch_contract: true,
            htl: 5,
            visited: VisitedPeers::new(&tx),
            subscribe: false,
        }));
        assert!(matches!(
            classify(msg),
            AttemptOutcome::Terminal(Terminal::LocalCompletion)
        ));
    }

    #[test]
    fn classify_response_found_without_state_is_unexpected() {
        // Defensive: if a peer somehow returns Found but the inner
        // StoreResponse has no state, the driver must NOT build an
        // InlineFound Terminal with a missing state.
        let tx = dummy_tx();
        let key = dummy_key();
        let msg = NetMessage::V1(NetMessageV1::Get(GetMsg::Response {
            id: tx,
            instance_id: *key.id(),
            result: GetMsgResult::Found {
                key,
                value: StoreResponse {
                    state: None,
                    contract: None,
                },
            },
            hop_count: 0,
        }));
        assert!(matches!(classify(msg), AttemptOutcome::Unexpected));
    }

    #[test]
    fn classify_unexpected_for_non_get_message() {
        let tx = dummy_tx();
        let msg = NetMessage::V1(NetMessageV1::Aborted(tx));
        assert!(matches!(classify(msg), AttemptOutcome::Unexpected));
    }

    #[test]
    fn max_retries_boundary_exhausts_at_limit() {
        let mut retries: usize = 0;
        for _ in 0..MAX_RETRIES {
            assert!(retries < MAX_RETRIES, "should not exhaust before limit");
            retries += 1;
        }
        assert!(
            retries >= MAX_RETRIES,
            "should exhaust at MAX_RETRIES={MAX_RETRIES}"
        );
    }

    /// Regression for the peer-dashboard prediction-graph data-collection
    /// regression: the client GET driver must emit a TIMED
    /// `RouteOutcome::Success { time_to_response_start, payload_size,
    /// payload_transfer_time }` on the success path so the router's
    /// `response_start_time_estimator` and `transfer_rate_estimator`
    /// receive observations. Before this fix the driver always emitted
    /// `RouteOutcome::SuccessUntimed`, leaving the Response Time and
    /// Transfer Rate charts on the peer dashboard permanently empty.
    #[test]
    fn drive_client_get_inner_emits_timed_success_on_success_path() {
        let src = production_source();
        let inner_body = extract_fn_body(src, "async fn drive_client_get_inner(");
        let build_body =
            extract_fn_body(src, "fn build_request(&mut self, attempt_tx: Transaction)");
        let classify_body = extract_fn_body(src, "fn classify(&mut self, reply: NetMessage)");

        // Driver must capture send time at attempt construction. The
        // body must use `tokio::time::Instant::now()` — `std::time::Instant::now()`
        // is banned in `crates/core/` by Rule Lint (see
        // .claude/rules/code-style.md) AND would not virtualize under
        // `start_paused(true)` in DST simulation tests.
        assert!(
            build_body.contains("self.request_sent_at = Some(tokio::time::Instant::now())"),
            "GetRetryDriver::build_request must capture request_sent_at via \
             tokio::time::Instant::now(); without this the Done branch has \
             no `time_to_response_start`."
        );
        // Driver must capture receive time on Terminal classification.
        assert!(
            classify_body.contains("self.response_received_at = Some(tokio::time::Instant::now())"),
            "GetRetryDriver::classify must capture response_received_at on \
             Terminal via tokio::time::Instant::now(); without this the Done \
             branch has no `time_to_response_start`."
        );
        // Done branch must construct a timed Success with all three fields.
        assert!(
            inner_body.contains("RouteOutcome::Success {")
                && inner_body.contains("time_to_response_start")
                && inner_body.contains("payload_size")
                && inner_body.contains("payload_transfer_time"),
            "drive_client_get_inner Done branch must build RouteOutcome::Success \
             with time_to_response_start + payload_size + payload_transfer_time. \
             Emitting SuccessUntimed instead leaves the router's response-time \
             and transfer-rate estimators with zero observations forever \
             (Failure-Probability-only peer-dashboard regression)."
        );
        // SuccessUntimed remains as a fallback when timing was not captured
        // (e.g., Request-echo / LocalCompletion paths).
        assert!(
            inner_body.contains("RouteOutcome::SuccessUntimed"),
            "Done branch must keep a SuccessUntimed fallback for paths \
             without timing capture."
        );
        // The streaming path must use the wire-authoritative `total_size`
        // rather than re-querying the store after assembly. Re-querying
        // races a concurrent UPDATE on the same contract and can also
        // return 0 if the LRU evicted the entry under cache pressure —
        // both failure modes silently zero out the transfer-rate sample.
        assert!(
            inner_body.contains("payload_size = *total_size as usize"),
            "Streaming branch must use wire-authoritative total_size for \
             payload_size, not a post-assembly store re-query."
        );
        // The `Terminal::LocalCompletion` arm is a loopback Request-echo
        // with no wire round-trip. Emitting timed Success there would
        // poison the response-time model with sub-millisecond loopback
        // samples attributed to the selected target peer.
        assert!(
            inner_body.contains("matches!(terminal, Terminal::LocalCompletion)"),
            "Done branch must skip timed Success for Terminal::LocalCompletion \
             (loopback Request-echo — no network round-trip to measure)."
        );
    }

    /// Regression: when the GET retry loop exhausts all peers without a
    /// Terminal classification, no `RouteOutcome::Success` is emitted.
    /// A future "always emit a final route-event" refactor would silently
    /// poison the success estimator with timed entries from peers that
    /// returned NotFound for the whole retry chain.
    #[test]
    fn drive_client_get_inner_exhausted_does_not_emit_success() {
        let src = production_source();
        let inner_body = extract_fn_body(src, "async fn drive_client_get_inner(");
        let exhausted_pos = inner_body
            .find("RetryLoopOutcome::Exhausted(")
            .expect("Done/Exhausted match must exist");
        let exhausted_arm = &inner_body[exhausted_pos..];
        // Bound the arm to the next match-arm by clipping at the next
        // top-level `RetryLoopOutcome::` token.
        let arm_end = exhausted_arm[1..]
            .find("RetryLoopOutcome::")
            .map(|p| p + 1)
            .unwrap_or(exhausted_arm.len());
        let arm_body = &exhausted_arm[..arm_end];
        assert!(
            !arm_body.contains("RouteOutcome::Success {"),
            "Exhausted arm must NOT emit a timed RouteOutcome::Success — \
             that would poison the response-time/transfer-rate estimators \
             with synthetic data for peers that never produced a Terminal."
        );
        assert!(
            !arm_body.contains("routing_finished("),
            "Exhausted arm must NOT call routing_finished — no wire success \
             attribution is appropriate for a peer set that returned NotFound."
        );
    }

    #[test]
    fn driver_outcome_exhausted_produces_client_error() {
        let cause = "GET to contract failed after 3 attempts".to_string();
        let outcome: DriverOutcome = match RetryLoopOutcome::<()>::Exhausted(cause) {
            RetryLoopOutcome::Exhausted(cause) => {
                DriverOutcome::Publish(Err(ErrorKind::OperationError {
                    cause: cause.into(),
                }
                .into()))
            }
            RetryLoopOutcome::Done(_)
            | RetryLoopOutcome::Unexpected
            | RetryLoopOutcome::InfraError(_) => unreachable!(),
        };
        assert!(
            matches!(outcome, DriverOutcome::Publish(Err(_))),
            "Exhaustion must produce a client error, not be swallowed"
        );
    }

    /// Extract the non-test source of `op_ctx_task.rs` by truncating
    /// at the `#[cfg(test)]` marker. Used by the bug-reproduction
    /// source-scrape tests below so that comments inside this test
    /// module don't create false positives.
    fn production_source() -> &'static str {
        const FULL: &str = include_str!("op_ctx_task.rs");
        let cutoff = FULL
            .find("#[cfg(test)]")
            .expect("file must have a #[cfg(test)] section");
        // The str literal outlives `cutoff`; slicing gives a &'static str.
        &FULL[..cutoff]
    }

    /// Isolate the body of a named function inside production source.
    fn extract_fn_body<'a>(source: &'a str, signature_prefix: &str) -> &'a str {
        let start = source
            .find(signature_prefix)
            .unwrap_or_else(|| panic!("could not find {signature_prefix}"));
        // Find the opening `{` of the body.
        let brace = source[start..].find('{').expect("fn sig must have body");
        let body_start = start + brace + 1;
        // Walk to the matching closing brace, tracking nesting.
        let bytes = source.as_bytes();
        let mut depth: i32 = 1;
        let mut i = body_start;
        while i < bytes.len() {
            match bytes[i] {
                b'{' => depth += 1,
                b'}' => {
                    depth -= 1;
                    if depth == 0 {
                        return &source[body_start..i];
                    }
                }
                _ => {}
            }
            i += 1;
        }
        panic!("unterminated fn body for {signature_prefix}");
    }

    /// Bug #3 reproduction: the legacy Response{Found} branch at
    /// `get.rs:2218-2241` reads the local store via
    /// `ContractHandlerEvent::GetQuery` FIRST, compares the stored bytes
    /// against the incoming `value`, and skips the `PutQuery` entirely
    /// when they match. This prevents re-invoking `update_state()` on
    /// contracts that implement idempotency checks (see #2018). The
    /// driver's `cache_contract_locally` must replicate
    /// this idempotency short-circuit.
    #[test]
    fn cache_contract_locally_has_state_matches_short_circuit() {
        let src = production_source();
        let body = extract_fn_body(src, "async fn cache_contract_locally(");
        // A proper idempotency short-circuit reads the local state
        // first (GetQuery BEFORE PutQuery) and compares bytes.
        let get_pos = body
            .find("ContractHandlerEvent::GetQuery")
            .unwrap_or(usize::MAX);
        let put_pos = body
            .find("ContractHandlerEvent::PutQuery")
            .unwrap_or(usize::MAX);
        let has_byte_compare = body.contains("as_ref() ==") || body.contains("state_matches");
        let has_short_circuit = get_pos < put_pos && has_byte_compare;
        assert!(
            has_short_circuit,
            "cache_contract_locally is missing the state_matches idempotency \
             short-circuit from the legacy Response{{Found}} branch \
             (get.rs:2218-2241). Without it the driver re-invokes PutQuery \
             on identical state — regressing issue #2018 for contracts \
             that enforce idempotency in update_state()."
        );
    }

    /// Bug #4 reproduction: the legacy branch at `get.rs:2420-2435`
    /// logs on PutQuery error but **continues** to run the hosting /
    /// interest / access-tracking side effects. Hosting LRU / TTL
    /// must refresh for ANY successful wire-level GET, not only when
    /// the local store write succeeded.
    ///
    /// After the fix the side effects live OUTSIDE the PutQuery match:
    /// the match result feeds a `put_persisted: bool` and
    /// `record_get_access` / `announce_contract_hosted` run after the
    /// match closes — reachable from state-matches, PutQuery-Ok, and
    /// PutQuery-Err paths alike. We pin that structure here by
    /// requiring the `record_get_access` call to appear AFTER the
    /// PutResponse match arms (identified by the `Err(err)` arm) in
    /// the source order.
    #[test]
    fn cache_contract_locally_runs_side_effects_on_put_error() {
        let src = production_source();
        let body = extract_fn_body(src, "async fn cache_contract_locally(");
        let err_arm = body
            .find("new_value: Err(")
            .expect("PutResponse Err arm must exist");
        let side_effect = body
            .find("record_get_access")
            .expect("record_get_access must be called");
        assert!(
            side_effect > err_arm,
            "record_get_access must run AFTER the PutResponse match \
             (outside both Ok and Err arms) so hosting LRU/TTL refresh on \
             any successful wire-level GET — including when the local \
             executor rejects the PutQuery. The legacy branch at \
             get.rs:2420-2435 continues these side effects on error; \
             the driver must match."
        );
    }

    /// Bug #2 reproduction (source-level): the legacy branch calls
    /// `auto_subscribe_on_get_response` for any client-initiated GET
    /// when `AUTO_SUBSCRIBE_ON_GET` is true (see `get.rs:2313, 2408`).
    /// The driver currently never calls it; `maybe_subscribe_child`
    /// only handles the explicit `subscribe=true` flag. This test
    /// pairs with `test_driver_inline_get_triggers_auto_subscribe`
    /// (integration) to lock down both the absence and the symptom.
    #[test]
    fn driver_calls_auto_subscribe_on_get_response() {
        let src = production_source();
        assert!(
            src.contains("auto_subscribe_on_get_response"),
            "The driver must invoke `auto_subscribe_on_get_response` on \
             successful GET terminal paths (AUTO_SUBSCRIBE_ON_GET = true in \
             ring.rs:60). The legacy branch does this at get.rs:2313/2408/3136/3185; \
             the driver must mirror it so client GETs with subscribe=false \
             still register the fallback subscription."
        );
    }

    /// Bug #5 reproduction (source-level): `record_op_result` in the
    /// Done arm must NOT be emitted unconditionally as success — if
    /// `build_host_response` returned `Err`, the telemetry should
    /// reflect failure. Otherwise the router's prediction model and
    /// the network_status dashboard say "GET succeeded" while the
    /// client sees an OperationError.
    #[test]
    fn record_op_result_reflects_host_result_outcome() {
        const SOURCE: &str = include_str!("op_ctx_task.rs");
        // Find the Done arm (the `RetryLoopOutcome::Done` branch).
        let done_arm_start = SOURCE
            .find("RetryLoopOutcome::Done(")
            .expect("Done arm must exist");
        let next_arm = SOURCE[done_arm_start..]
            .find("RetryLoopOutcome::Exhausted")
            .expect("Exhausted arm must follow");
        let arm = &SOURCE[done_arm_start..done_arm_start + next_arm];
        // Locate the record_op_result call inside the arm.
        let call_pos = arm
            .find("record_op_result")
            .expect("record_op_result must be called in Done arm");
        // Get the surrounding ~200 chars to inspect the success flag.
        let tail = &arm[call_pos..];
        let call_window = &tail[..tail.len().min(200)];
        // Unconditional `true` is the bug. A proper implementation
        // derives the success flag from `host_result.is_ok()` or a
        // similarly named value.
        let looks_unconditional = call_window.contains("true,") && !call_window.contains("is_ok()");
        assert!(
            !looks_unconditional,
            "record_op_result in the Done arm is passed an unconditional \
             `true`. The success flag must track `host_result.is_ok()` so \
             telemetry does not diverge from the client-visible outcome. \
             Call window: {call_window}"
        );
    }

    /// Non-bug: per #3757, the node ALWAYS requests contract code on
    /// the wire regardless of what the client asked for, so it can
    /// cache WASM for validation/hosting. The driver matches legacy
    /// `start_op` behaviour (`get.rs:59` hard-codes the same value).
    /// This test pins the intentional choice so a future refactor
    /// doesn't silently reintroduce client-flag pass-through.
    #[test]
    fn driver_hardcodes_fetch_contract_true_per_issue_3757() {
        let src = production_source();
        let build_body = extract_fn_body(
            src,
            "fn build_request(&mut self, attempt_tx: Transaction) -> NetMessage {",
        );
        assert!(
            build_body.contains("fetch_contract: true,"),
            "GetMsg::Request.fetch_contract must stay hard-coded `true` — \
             the node needs WASM for local validation/hosting regardless of \
             the client's return_contract_code preference (issue #3757 / \
             get.rs:52-55)."
        );
    }

    /// Bug #1 regression: `Terminal::Streaming` in the Done arm must
    /// invoke `assemble_and_cache_stream` so that streamed GET
    /// responses actually write the contract state into the local
    /// executor. Without this call, a cold-cache client GET of a
    /// \>threshold contract succeeds on the wire but leaves the
    /// originator's local store empty — the client gets
    /// `OperationError` via `build_host_response`'s re-query miss.
    ///
    /// The simulation-level driver-isolation tests for this path are
    /// `#[ignore]`'d pending infrastructure work (#3883); this
    /// source-scrape pins the wiring so the call can't be silently
    /// removed.
    #[test]
    fn streaming_terminal_calls_assemble_and_cache_stream() {
        let src = production_source();
        // Since #4345, assembly runs inside `drive_get_with_assembly_retry`
        // (so a failed assembly can advance to the next candidate and
        // re-enter the retry loop). Both drivers must route through the
        // wrapper, and the wrapper must perform the assemble+cache.
        let client_body = extract_fn_body(src, "async fn drive_client_get_inner(");
        assert!(
            client_body.contains("drive_get_with_assembly_retry("),
            "drive_client_get_inner must drive the loop via \
             `drive_get_with_assembly_retry`. Without it, cold-cache \
             streaming GETs return OperationError because nothing writes \
             the local store (bug #1 in PR #3884 review), and assembly \
             failures burn the whole GET without consuming the retry \
             budget (#4345)."
        );
        let sub_op_body = extract_fn_body(src, "async fn drive_sub_op_get(");
        assert!(
            sub_op_body.contains("drive_get_with_assembly_retry("),
            "drive_sub_op_get must drive the loop via \
             `drive_get_with_assembly_retry` — the sub-op path has the \
             same assembly-failure-burns-the-op gap as the client path \
             (#4345)."
        );
        let wrapper_body = extract_fn_body(src, "async fn drive_get_with_assembly_retry(");
        assert!(
            wrapper_body.contains("assemble_and_cache_stream("),
            "drive_get_with_assembly_retry must call \
             `assemble_and_cache_stream` on the Streaming terminal."
        );
    }

    /// #4345: a failed stream assembly must be a *retryable* attempt
    /// failure — advance to the next candidate, fresh attempt tx — and
    /// exhaustion must still surface as `Done` (OperationError), never
    /// as `Exhausted` (which the caller maps to a false `NotFound`:
    /// a streaming header proves the contract exists).
    #[test]
    fn assembly_failure_advances_with_fresh_tx_and_never_exhausts_to_notfound() {
        let src = production_source();
        let body = extract_fn_body(src, "async fn drive_get_with_assembly_retry(");

        // Anchor on the assembly call first so a future earlier
        // `Err(e)` arm (e.g. around the claim) can't silently shift
        // the slice this test inspects.
        let assemble_call = body
            .find("match assemble_and_cache_stream")
            .expect("wrapper must match on assemble_and_cache_stream");
        let err_arm = body[assemble_call..]
            .find("Err(e) =>")
            .map(|p| p + assemble_call)
            .expect("wrapper must handle assembly Err");
        let err_body = &body[err_arm..];

        // The routing penalty must land on the candidate whose header
        // never became a stream — capture it BEFORE advance() mutates
        // `current_target`.
        let capture_pos = err_body
            .find("let failed_target = driver.current_target.clone()")
            .expect("Err arm must capture the failing target");
        let advance_pos = err_body
            .find("driver.advance()")
            .expect("Err arm must call driver.advance()");
        assert!(
            capture_pos < advance_pos,
            "failed_target must be captured BEFORE driver.advance() — \
             advance() replaces current_target, so capturing after \
             penalizes the wrong (fresh) candidate."
        );

        // Re-entry must use a fresh attempt tx: reusing the previous tx
        // collides with the relay dedup gates (`active_relay_get_txs`)
        // while the failed attempt's relay chain is still draining.
        assert!(
            err_body.contains("attempt_tx = driver.new_attempt_tx()"),
            "assembly-failure retry must re-enter the loop with a fresh \
             attempt tx via driver.new_attempt_tx()"
        );

        // The advancing path must penalize the failed candidate (the
        // router only learns about header-without-stream peers from
        // this call) and must remember the header for the
        // wire-exhaustion conversion below.
        let next_arm = err_body
            .find("AdvanceOutcome::Next =>")
            .expect("Err arm must handle Next");
        let next_body = &err_body[next_arm
            ..err_body
                .find("AdvanceOutcome::Exhausted =>")
                .expect("Err arm must handle Exhausted")];
        assert!(
            next_body.contains("emit_get_route_failure("),
            "the advancing path must emit a route failure for the \
             failed candidate (gated on emit_route_failure_on_retry)"
        );
        assert!(
            next_body
                .contains("failed_header = Some((key, stream_id, includes_contract, total_size))"),
            "the advancing path must remember the streaming header so a \
             later wire exhaustion can't surface as a false NotFound"
        );

        // Exhaustion keeps the Done(Streaming) outcome. The wrapper
        // only reaches the assembly Err arm after `result` matched
        // `Done(Terminal::Streaming { .. })`, so `break result` returns
        // that original outcome unchanged.
        let exhausted_arm = err_body
            .find("AdvanceOutcome::Exhausted =>")
            .expect("Err arm must handle Exhausted");
        let exhausted_body = &err_body[exhausted_arm..];
        assert!(
            exhausted_body.contains("break result"),
            "exhausted assembly retries must break with the original \
             Done(Streaming) outcome (`break result`) so the client sees \
             OperationError, NOT RetryLoopOutcome::Exhausted (which maps \
             to a false NotFound for a contract that provably exists)."
        );
        assert!(
            !exhausted_body.contains("RetryLoopOutcome::Exhausted("),
            "exhausted assembly retries must not be converted into \
             RetryLoopOutcome::Exhausted"
        );
        // ...and the budget-exhausted path must NOT emit a route
        // failure: the caller's final route event (driven by the
        // failed host_result) already records the Failure for the
        // last target — emitting here too would double-count it.
        assert!(
            !exhausted_body.contains("emit_get_route_failure("),
            "the budget-exhausted path must not emit a per-retry route \
             failure — the caller's final Failure event covers the last \
             target (double-count otherwise)"
        );

        // Wire exhaustion AFTER a failed assembly must convert back to
        // the remembered Done(Streaming): a header proved the contract
        // exists, so RetryLoopOutcome::Exhausted (mapped to NotFound by
        // both callers) would be a false NotFound. This state is only
        // reachable post-#4345 (assembly failure re-enters the loop).
        let exhausted_passthrough = body
            .find("RetryLoopOutcome::Exhausted(cause) =>")
            .expect("wrapper must have an Exhausted pass-through arm");
        let passthrough_body = &body[exhausted_passthrough..];
        assert!(
            passthrough_body.contains(
                "if let Some((key, stream_id, includes_contract, total_size)) = failed_header"
            ),
            "the Exhausted pass-through must check failed_header"
        );
        assert!(
            passthrough_body.contains("break RetryLoopOutcome::Done(Terminal::Streaming {"),
            "wire exhaustion after a seen streaming header must convert \
             back to Done(Streaming) so the client sees OperationError, \
             not a false NotFound"
        );
    }

    /// #4345: the synthesized client error must carry the assembly
    /// failure cause when one occurred, and fall back to the generic
    /// store-lookup message otherwise. Behavioral coverage for the
    /// cause construction both callers use on the exhaustion path.
    #[test]
    fn synthesized_error_causes_carry_assembly_failure() {
        let instance_id = ContractInstanceId::new([0xC1; 32]);

        let with_assembly = synthesized_get_error_cause(
            &instance_id,
            Some("stream assembly: no fragments received within inactivity timeout"),
        );
        assert!(
            with_assembly.contains("stream assembly failed")
                && with_assembly.contains("no fragments received"),
            "assembly-exhaustion cause must be diagnostic: {with_assembly}"
        );

        let without = synthesized_get_error_cause(&instance_id, None);
        assert!(
            without.contains("local store lookup failed"),
            "fallback cause must keep the store-lookup message: {without}"
        );
        assert!(
            !without.contains("assembly"),
            "fallback cause must not mention assembly: {without}"
        );

        let sub_with = sub_op_not_found_cause(&instance_id, Some("injected failure"));
        assert!(
            sub_with.contains(&missing_state_cause(&instance_id))
                && sub_with.contains("injected failure"),
            "sub-op cause must append the assembly failure: {sub_with}"
        );
        assert_eq!(
            sub_op_not_found_cause(&instance_id, None),
            missing_state_cause(&instance_id)
        );
    }

    /// #4345: the injection budget is keyed by contract so parallel
    /// tests in one process can't consume each other's failures.
    #[test]
    fn assembly_fault_injection_is_per_key_and_bounded() {
        let key_a = ContractKey::from_id_and_code(
            ContractInstanceId::new([0xA1; 32]),
            CodeHash::new([0xA2; 32]),
        );
        let key_b = ContractKey::from_id_and_code(
            ContractInstanceId::new([0xB1; 32]),
            CodeHash::new([0xB2; 32]),
        );

        // Unarmed keys never fail.
        assert!(!assembly_fault_injection::consume(&key_b));

        assembly_fault_injection::inject_failures(key_a, 2);
        assert!(assembly_fault_injection::consume(&key_a));
        // Other keys are unaffected while a budget is armed.
        assert!(!assembly_fault_injection::consume(&key_b));
        assert!(assembly_fault_injection::consume(&key_a));
        // Budget exhausted → assembly succeeds again.
        assert!(!assembly_fault_injection::consume(&key_a));
    }

    /// Pure-data regression test for the streaming payload shape the
    /// driver deserializes. Locks down the invariant that
    /// `GetStreamingPayload` round-trips via bincode, so a regression
    /// that changes the wire format would break `assemble_and_cache_stream`
    /// loudly at this level instead of silently producing an empty
    /// store (bug #1 class).
    #[test]
    fn streaming_payload_round_trips_via_bincode() {
        let key = dummy_key();
        let state_bytes = vec![0x42u8; 512];
        let payload = GetStreamingPayload {
            key,
            value: StoreResponse {
                state: Some(WrappedState::new(state_bytes.clone())),
                contract: None,
            },
        };
        let encoded = bincode::serialize(&payload).expect("bincode encode");
        let decoded: GetStreamingPayload = bincode::deserialize(&encoded).expect("bincode decode");
        assert_eq!(decoded.key, key);
        assert_eq!(
            decoded.value.state.as_ref().map(|s| s.as_ref().to_vec()),
            Some(state_bytes),
            "state bytes must round-trip through the streaming payload"
        );
    }

    /// Bug #1 follow-through: `assemble_and_cache_stream` must claim
    /// the stream by `(peer_addr, stream_id)`, await assembly, and
    /// check the key matches before caching. The source-scrape
    /// verifies the function's structure hasn't been simplified in a
    /// way that would skip any of those steps.
    #[test]
    fn assemble_and_cache_stream_performs_claim_assemble_key_check() {
        let src = production_source();
        let body = extract_fn_body(src, "async fn assemble_and_cache_stream(");

        assert!(
            body.contains("orphan_stream_registry") && body.contains("claim_or_wait"),
            "assemble_and_cache_stream must claim the stream via \
             orphan_stream_registry().claim_or_wait()"
        );
        assert!(
            body.contains(".assemble()") && body.contains(".await"),
            "assemble_and_cache_stream must await stream assembly"
        );
        assert!(
            body.contains("GetStreamingPayload") && body.contains("bincode::deserialize"),
            "assemble_and_cache_stream must deserialize the payload \
             as GetStreamingPayload"
        );
        assert!(
            body.contains("payload.key != expected_key"),
            "assemble_and_cache_stream must verify the stream payload's \
             key matches the expected ContractKey — a mismatch would \
             silently cache the wrong contract under the expected key"
        );
        assert!(
            body.contains("cache_contract_locally"),
            "assemble_and_cache_stream must delegate the actual write \
             and hosting side effects to cache_contract_locally"
        );
    }

    /// Guard against subscribe firing when the client did not request it.
    /// Source-scrape to verify `maybe_subscribe_child` short-circuits on
    /// `!subscribe`. Mirrors the spirit of PUT 3a's
    /// `finalize_put_at_originator_never_subscribes_from_driver`.
    #[test]
    fn maybe_subscribe_child_short_circuits_on_false() {
        const SOURCE: &str = include_str!("op_ctx_task.rs");
        let fn_start = SOURCE
            .find("async fn maybe_subscribe_child(")
            .expect("maybe_subscribe_child must exist");
        let body = &SOURCE[fn_start..];
        body.find("if !subscribe {")
            .expect("maybe_subscribe_child must short-circuit on !subscribe");
    }

    // ── Relay driver source-scrape tests (#3883) ─────────────────────────────
    //
    // These tests validate the structural invariants of the relay GET driver
    // without requiring a full simulation harness.  They mirror the pattern
    // established by the client driver tests above.

    /// T1: HTL=0 short-circuit must send NotFound upstream without entering
    /// the retry loop.  The source must contain the htl==0 guard BEFORE the
    /// first `relay_advance_to_next_peer` call.
    #[test]
    fn relay_driver_htl_zero_guard_precedes_retry_loop() {
        let src = production_source();
        let body = extract_fn_body(src, "async fn drive_relay_get_inner<CB>(");
        let htl_guard = body
            .find("if htl == 0")
            .expect("drive_relay_get_inner must have an `if htl == 0` guard");
        let retry_loop = body
            .find("relay_advance_to_next_peer")
            .expect("drive_relay_get_inner must call relay_advance_to_next_peer");
        assert!(
            htl_guard < retry_loop,
            "HTL=0 guard must appear BEFORE the retry loop; \
             otherwise HTL exhaustion enters the retry loop and forwards unnecessarily"
        );
    }

    /// T2: Local cache short-circuit must send Found upstream without entering
    /// the retry loop.  The source must contain the local-cache check BEFORE
    /// `relay_advance_to_next_peer` and AFTER the HTL guard.
    #[test]
    fn relay_driver_local_cache_check_precedes_retry_loop() {
        let src = production_source();
        let body = extract_fn_body(src, "async fn drive_relay_get_inner<CB>(");
        let local_check = body
            .find("check_local_with_interest_gate")
            .expect("drive_relay_get_inner must call check_local_with_interest_gate");
        let retry_loop = body
            .find("relay_advance_to_next_peer")
            .expect("drive_relay_get_inner must call relay_advance_to_next_peer");
        assert!(
            local_check < retry_loop,
            "Local-cache check must appear BEFORE the retry loop; \
             otherwise a hosting relay forwards instead of answering immediately"
        );
    }

    /// T3: Interest gate in `check_local_with_interest_gate` — stale cache
    /// (no local interest) must NOT return a local_value (must go to fallback).
    #[test]
    fn check_local_with_interest_gate_has_interest_check() {
        let src = production_source();
        let body = extract_fn_body(src, "async fn check_local_with_interest_gate(");
        assert!(
            body.contains("has_local_interest"),
            "check_local_with_interest_gate must call `has_local_interest` to gate \
             whether stale cache is served immediately or deferred to network"
        );
        // The stale-cache branch must put the value into the fallback slot,
        // not into local_value.
        assert!(
            body.contains("None, Some("),
            "check_local_with_interest_gate must return (None, Some(fallback)) \
             when there is local state but no active interest"
        );
    }

    /// T4: Downstream `Response{Found}` must forward upstream FIRST,
    /// then cache locally. This pins the issue #4155 fix: caching runs
    /// WASM `validate_state` on the single-threaded contract_handling
    /// event loop and can take seconds. Forwarding first keeps cache
    /// time off the upstream-visible critical path. The relay STILL
    /// caches (just after forwarding) so local LRU/TTL and
    /// `announce_contract_hosted` semantics are preserved.
    ///
    /// Reverting this ordering — putting `cache_contract_locally`
    /// before `relay_send_found` — re-introduces the per-hop dwell
    /// latency that #4155 was opened to fix.
    #[test]
    fn relay_driver_forwards_upstream_before_caching_on_found_response() {
        let src = production_source();
        let body = extract_fn_body(src, "async fn drive_relay_get_inner<CB>(");
        // Find the InlineFound arm inside the loop.
        let found_arm = body
            .find("Terminal::InlineFound {")
            .expect("drive_relay_get_inner must handle Terminal::InlineFound");
        let tail = &body[found_arm..];
        // The arm must STILL cache locally — caching is opportunistic
        // but load-bearing for hosting LRU/TTL.
        let cache_pos = tail.find("cache_contract_locally").unwrap_or(usize::MAX);
        let send_pos = tail.find("relay_send_found").unwrap_or(usize::MAX);
        assert!(
            cache_pos != usize::MAX,
            "relay InlineFound arm must STILL call cache_contract_locally — \
             caching is opportunistic but load-bearing for LRU/TTL and \
             `announce_contract_hosted` semantics"
        );
        assert!(
            send_pos != usize::MAX,
            "relay InlineFound arm must call relay_send_found"
        );
        assert!(
            send_pos < cache_pos,
            "issue #4155: relay_send_found must be called BEFORE \
             cache_contract_locally in the InlineFound arm. Caching first \
             blocks the upstream-visible forward behind WASM validate_state \
             on the single-threaded contract_handling event loop, which is \
             the root cause of the per-hop dwell observed in #4155"
        );
    }

    /// T4b: All three relay-driver callsites must forward upstream
    /// BEFORE caching locally (issue #4155). Mirrors T4 for the other
    /// two relay paths that the source-scrape
    /// `all_relay_callsites_pass_is_client_requester_false` test already
    /// recognizes (R4 immediate-serve, R10 exhaustion fallback, R12a
    /// bubble-up).
    #[test]
    fn all_relay_callsites_forward_before_caching() {
        let src = production_source();
        let body = extract_fn_body(src, "async fn drive_relay_get_inner<CB>(");

        // For each relay-style block in the function, when both
        // `relay_send_found(` and `cache_contract_locally(` appear, the
        // forward must come first. We scan all paired occurrences.
        let send_positions: Vec<usize> = body
            .match_indices("relay_send_found(")
            .map(|(i, _)| i)
            .collect();
        let cache_positions: Vec<usize> = body
            .match_indices("cache_contract_locally(")
            .map(|(i, _)| i)
            .collect();
        assert_eq!(
            send_positions.len(),
            3,
            "drive_relay_get_inner should have exactly three \
             `relay_send_found(` callsites (R4 immediate, R10 fallback, \
             R12a bubble-up). Found {} — a refactor has changed the shape.",
            send_positions.len(),
        );
        assert_eq!(
            cache_positions.len(),
            5,
            "drive_relay_get_inner should have exactly five \
             `cache_contract_locally(` callsites (R4, R10, R12a, plus the \
             two #4307 streaming-arm caches). Found {} — a refactor has \
             changed the shape.",
            cache_positions.len(),
        );
        // Pair the three `relay_send_found` callsites (R4, R10, R12a) with
        // their corresponding inline-Found caches and verify each `send`
        // comes before its `cache`. The streaming-arm caches (positions
        // 4 and 5) forward via `pipe_stream` rather than `relay_send_found`
        // and are covered by `relay_streaming_arm_forwards_before_caching`,
        // so they are intentionally excluded from this positional pairing.
        // The three sends all precede the streaming arm in source order, so
        // zipping against the first three caches is correct.
        for (idx, (send_pos, cache_pos)) in send_positions
            .iter()
            .zip(cache_positions.iter())
            .enumerate()
        {
            assert!(
                send_pos < cache_pos,
                "issue #4155: relay callsite #{idx} must forward upstream \
                 (`relay_send_found`) BEFORE caching locally \
                 (`cache_contract_locally`). Found send at {send_pos}, \
                 cache at {cache_pos}."
            );
        }
    }

    /// T5: Exhaustion path must send NotFound upstream.
    #[test]
    fn relay_driver_exhaustion_sends_not_found_upstream() {
        let src = production_source();
        let body = extract_fn_body(src, "async fn drive_relay_get_inner<CB>(");
        // Find the exhaustion branch (None arm of relay_advance_to_next_peer).
        assert!(
            body.contains("relay_send_not_found"),
            "drive_relay_get_inner must call `relay_send_not_found` on exhaustion"
        );
    }

    /// T6 (superseded): Originally required `relay_send_forwarding_ack`
    /// to be emitted before the downstream send. That ack collided with
    /// the upstream relay driver's capacity-1 `pending_op_results`
    /// waiter (the ack carried `incoming_tx`, which equals the
    /// upstream's `attempt_tx` on a relay-to-relay hop). The waiter
    /// would fire on the ack, return `AttemptOutcome::Unexpected`, and
    /// cause the upstream to immediately retry with a fresh tx — which
    /// the downstream's dispatch gate saw as a brand-new Request and
    /// spawned another full relay subtree. Net amplification was
    /// 3^HTL spawns per origination, observed as 6.8M spawns and 63GB
    /// RSS in workflow runs 24600168871 / 24600634908 / 24601267577.
    ///
    /// Fix: drop the ack entirely from the driver relay driver.
    /// Upstream's `send_to_and_await` still has OPERATION_TTL (60s) to
    /// receive the real Response, which is what legacy effectively had
    /// minus the ack-driven timer extension.
    #[test]
    fn relay_driver_does_not_send_forwarding_ack() {
        let src = production_source();
        let body = extract_fn_body(src, "async fn drive_relay_get_inner<CB>(");
        assert!(
            !body.contains("relay_send_forwarding_ack"),
            "drive_relay_get_inner must NOT call relay_send_forwarding_ack \
             — the ack collided with upstream's attempt_tx waiter and \
             amplified spawns (workflow 24600634908: 6.8M spawns, 63GB RSS)"
        );
        // A literal `GetMsg::ForwardingAck { ... }` construction would reintroduce
        // the bug. Comments/doc-strings mentioning "ForwardingAck" are fine.
        assert!(
            !body.contains("GetMsg::ForwardingAck {"),
            "drive_relay_get_inner must not construct GetMsg::ForwardingAck — \
             dropped to break the spawn-amplification cycle"
        );
    }

    /// T7: `relay_advance_to_next_peer` must respect incoming `VisitedPeers`
    /// by using the bloom filter as the skip list for `k_closest_potentially_hosting`.
    #[test]
    fn relay_advance_uses_visited_bloom_filter_as_skip_list() {
        let src = production_source();
        let body = extract_fn_body(src, "fn relay_advance_to_next_peer(");
        assert!(
            body.contains("k_closest_potentially_hosting"),
            "relay_advance_to_next_peer must use k_closest_potentially_hosting"
        );
        assert!(
            body.contains("new_visited"),
            "relay_advance_to_next_peer must pass new_visited as the skip list \
             so the upstream's VisitedPeers is respected"
        );
    }

    /// T8: Classify reuse — relay driver must call `classify` (the same
    /// function the client driver uses) for reply classification.
    #[test]
    fn relay_driver_reuses_classify_function() {
        let src = production_source();
        let body = extract_fn_body(src, "async fn drive_relay_get_inner<CB>(");
        assert!(
            body.contains("classify(reply)"),
            "drive_relay_get_inner must call `classify(reply)` to classify \
             downstream replies — reusing the client driver's classify avoids \
             duplicate terminal-variant handling"
        );
    }

    /// T9 (commit 2 version): start_relay_get is now live — the #[allow(dead_code)]
    /// attribute must have been removed when dispatch was wired in node.rs.
    ///
    /// This test replaces the commit-1 version that asserted the attribute WAS
    /// present. Now it asserts the attribute is ABSENT so a future refactor can't
    /// accidentally re-suppress the live driver with #[allow(dead_code)].
    #[test]
    fn relay_entry_point_no_longer_annotated_dead_code_after_commit2() {
        let src = production_source();
        let fn_start = src
            .find("pub(crate) async fn start_relay_get<CB>(")
            .expect("start_relay_get must exist");
        // Look in the 500 chars before the fn signature for the attribute.
        let window_start = fn_start.saturating_sub(500);
        let window = &src[window_start..fn_start];
        assert!(
            !window.contains("#[allow(dead_code)]"),
            "start_relay_get must NOT be annotated with #[allow(dead_code)] in commit 2 \
             — the driver is now live (wired in node.rs dispatch). Remove the attribute \
             to keep dead-code warnings effective."
        );
    }

    // ── Coverage-gap tests for PR #3896 (follow-up to T1-T9) ────────────────
    //
    // The T1-T9 suite above covers top-level structural ordering (guard-before-
    // loop, cache-before-send, ack-before-request, etc). The tests below
    // cover the behavioral contracts T1-T9 do NOT pin:
    //
    //   - G1/G2: dispatch gates in node.rs (source_addr=None loopback and
    //     has_get_op=true both fall through to legacy)
    //   - A   : HTL=0 emits NotFound upstream frame (not just logs-and-
    //     returns)
    //   - G/R10: downstream NotFound → exhaustion path; stale-cache
    //     fallback answers Found instead of NotFound when local state
    //     exists but interest is absent
    //   - R7  : ForwardingAck emitted exactly once, not per retry
    //   - R8  : wire-side Request propagation carries htl-1 and
    //     updated visited bloom
    //   - R12a→R13: send_found failure → compensating NotFound in outer
    //     `drive_relay_get` error funnel
    //   - R12b: streaming-downstream currently WARN+continue (regression
    //     guard until follow-up PR migrates streaming relay)
    //   - N   : concurrent same-key GET: gate condition at dispatch is
    //     per-tx (has_get_op), NOT per-key (by design; documented)
    //
    // All tests below are source-scrape style to match the T1-T9 shape —
    // they catch accidental code reorders or deletions without needing a
    // full turmoil harness. Behavioral coverage for the happy path is
    // already provided by `test_get_routing_coverage_low_htl` and
    // `test_get_reliability_*` (nightly).

    // ── Dispatch shape pin ────────────────────────────────────────────────
    //
    // The GET arm in node.rs dispatches every wire variant
    // unconditionally to a driver. Originator loopback
    // (`source_addr=None`) is mapped to `upstream_addr=own_addr`.
    // Structural guard lives at
    // `node::tests::callback_forward_tests::get_branch_dispatches_relay_driver`.

    #[test]
    fn relay_dispatch_target_is_start_relay_get() {
        const NODE_RS: &str = include_str!("../../node.rs");
        let arm_start = NODE_RS
            .find("NetMessageV1::Get(ref op) => {")
            .expect("Get arm must exist in handle_pure_network_message_v1");
        let next_variant = NODE_RS[arm_start..]
            .find("NetMessageV1::Update(ref op) => {")
            .expect("Update arm must follow Get arm")
            + arm_start;
        let arm = &NODE_RS[arm_start..next_variant];
        assert!(
            arm.contains("get::op_ctx_task::start_relay_get("),
            "GET arm must dispatch fresh inbound Request to \
             `get::op_ctx_task::start_relay_get`."
        );
    }

    // ── A: HTL=0 actually sends a NotFound frame upstream ──────────────────

    /// The HTL=0 short-circuit in `drive_relay_get_inner` must call
    /// `relay_send_not_found(..., upstream_addr)` (not just log+return).
    /// If this frame isn't emitted, the upstream peer waits for the full
    /// `OPERATION_TTL` (60s) instead of seeing a fast NotFound — a
    /// regression would show up as slow tail-latency under HTL-pressure,
    /// not as a functional failure.
    #[test]
    fn htl_zero_guard_emits_not_found_upstream_frame() {
        let src = production_source();
        let body = extract_fn_body(src, "async fn drive_relay_get_inner<CB>(");
        // Isolate the `if htl == 0 { ... }` block (before the retry loop).
        let guard_start = body.find("if htl == 0").expect("htl==0 guard must exist");
        let after_guard = &body[guard_start..];
        // Closing brace of the guard block — walk until depth returns to 0.
        let body_open = after_guard
            .find('{')
            .expect("htl==0 guard must have a body");
        let bytes = after_guard.as_bytes();
        let mut depth: i32 = 1;
        let mut i = body_open + 1;
        while i < bytes.len() && depth > 0 {
            match bytes[i] {
                b'{' => depth += 1,
                b'}' => depth -= 1,
                _ => {}
            }
            i += 1;
        }
        let guard_block = &after_guard[body_open..i];
        assert!(
            guard_block.contains("relay_send_not_found"),
            "HTL=0 guard block must call `relay_send_not_found(...)` so the \
             upstream gets a prompt NotFound frame instead of hanging until \
             OPERATION_TTL. Guard body was: {guard_block}"
        );
        assert!(
            guard_block.contains("upstream_addr"),
            "HTL=0 NotFound must be sent to `upstream_addr`, not any other \
             peer. Guard body was: {guard_block}"
        );
        assert!(
            guard_block.contains("return Ok(())"),
            "HTL=0 guard must return early after sending NotFound; otherwise \
             execution would fall into the retry loop with htl=0."
        );
    }

    // ── G/R10: Exhaustion path — NotFound vs stale-cache fallback ──────────

    /// Exhaustion (None from `relay_advance_to_next_peer`) must branch on
    /// `local_fallback`: with stale local state, serve Found from that
    /// state (R10); without, send NotFound (G/R11). A regression where
    /// both branches send NotFound silently loses availability for stale-
    /// cache relays (they would forward then lose the fallback even though
    /// they still hold the state locally).
    #[test]
    fn exhaustion_branches_on_local_fallback_presence() {
        let src = production_source();
        let body = extract_fn_body(src, "async fn drive_relay_get_inner<CB>(");
        // The None arm of the `match relay_advance_to_next_peer(...)` is the
        // exhaustion branch. It must contain both `local_fallback` disposition
        // AND both Found and NotFound sends.
        let none_arm = body
            .find("None => {")
            .expect("exhaustion arm (`None => {{`) must exist");
        // Clip to the matching close; the next `Some(p) => {` arm may precede
        // or follow, so take the whole match body from None onward up to the
        // end of the outer function block.
        let tail = &body[none_arm..];
        // Bound at the `return Ok(());` that ends the exhaustion branch.
        let clip = tail
            .find("return Ok(());")
            .expect("exhaustion branch must end with `return Ok(());`");
        let arm = &tail[..clip + "return Ok(());".len()];
        assert!(
            arm.contains("if let Some((key, state, contract)) = local_fallback"),
            "Exhaustion arm must branch on `local_fallback`; otherwise the \
             stale-cache fallback semantic (R3d → R10) is lost."
        );
        assert!(
            arm.contains("relay_send_found"),
            "Exhaustion arm must call `relay_send_found` when `local_fallback` \
             is Some — the stale-cache relay serves what it has after all \
             downstream peers NotFound."
        );
        assert!(
            arm.contains("relay_send_not_found"),
            "Exhaustion arm must call `relay_send_not_found` when \
             `local_fallback` is None — the non-caching relay bubbles \
             NotFound upstream."
        );
        // Ordering: the `else` branch (NotFound) must follow the `if Some`
        // branch (Found).
        let found_pos = arm.find("relay_send_found").unwrap();
        let not_found_pos = arm.find("relay_send_not_found").unwrap();
        assert!(
            found_pos < not_found_pos,
            "Fallback-Found must precede NotFound in the exhaustion arm \
             source order; a reversal would mean NotFound always runs first \
             and the fallback path is dead code."
        );
    }

    /// `check_local_with_interest_gate` must return the local state in
    /// the fallback slot (not `local_value`) when the relay holds state
    /// but `has_local_interest` is false. This locks down the interest
    /// gate: hosting relays serve immediately, stale-cache relays defer
    /// to the network and hold local state as a fallback.
    #[test]
    fn interest_gate_returns_fallback_when_not_actively_hosting() {
        let src = production_source();
        let body = extract_fn_body(src, "async fn check_local_with_interest_gate(");
        // The interest-gated branch structure must be:
        //   if !has_local_interest(&key) {
        //     (None, Some((key, state, contract)))
        //   } else {
        //     (Some((key, state, contract)), None)
        //   }
        let neg_gate = body
            .find("if !op_manager.interest_manager.has_local_interest(&key)")
            .expect("interest gate must check `!has_local_interest` branch explicitly");
        let tail = &body[neg_gate..];
        let stale_pos = tail.find("(None, Some(").expect("stale branch must exist");
        let active_pos = tail.find("(Some(").expect("active branch must exist");
        // active branch (Some(...), None) must come AFTER the stale branch in
        // the `else` arm.
        assert!(
            stale_pos < active_pos,
            "`if !has_local_interest` arm (stale → fallback slot) must appear \
             before the `else` arm (active → local_value slot) in source order."
        );
    }

    // ── R7 (superseded): ForwardingAck removed from driver relay ──────
    //
    // Superseded by `relay_driver_does_not_send_forwarding_ack` (T6
    // rewrite). The original latch logic was pinned here to ensure the
    // ack fired exactly once per relay invocation, which was the legacy
    // behavior. In the migration the ack's `id` collides
    // with the upstream relay driver's `attempt_tx` on its capacity-1
    // `pending_op_results` waiter — causing 3^HTL spawn amplification.
    // The ack is now never sent; see the T6 test for the invariant.

    // ── R8: Wire-side Request propagation (htl-1 + updated visited) ────────

    /// Each retry iteration must build a downstream `GetMsg::Request` with:
    ///   - `htl: new_htl` where `new_htl = htl.saturating_sub(1)`
    ///   - `visited: new_visited.clone()` (the bloom filter containing
    ///     own_addr and upstream_addr plus the caller's skip set)
    ///   - `id: incoming_tx` (reused across retries — matches legacy
    ///     end-to-end tx preservation; see the amplification comment
    ///     on that line for why the original per-iteration `attempt_tx`
    ///     caused 7M spawns / 100s in ci-fault-loss)
    ///
    /// Without `new_visited.clone()` the downstream relay's skip list is
    /// missing upstream hops, leading to loop formation.
    #[test]
    fn forwarded_request_decrements_htl_and_propagates_visited() {
        let src = production_source();
        let body = extract_fn_body(src, "async fn drive_relay_get_inner<CB>(");
        // The forwarded Request must be built with the decremented HTL.
        assert!(
            body.contains("let new_htl = htl.saturating_sub(1);"),
            "Retry loop must compute `new_htl = htl.saturating_sub(1)` so \
             the forwarded Request carries one-less HTL — otherwise the \
             downstream relay would forward with the same HTL and loops \
             could form."
        );
        // The forwarded Request body must thread `new_htl` and `new_visited`.
        let request_build = body
            .find("NetMessage::from(GetMsg::Request")
            .expect("retry loop must build the forwarded GetMsg::Request");
        // Take the next ~400 chars after the `GetMsg::Request {` opening as
        // the struct-literal window.
        let window = &body[request_build..(request_build + 400).min(body.len())];
        assert!(
            window.contains("htl: new_htl"),
            "Forwarded GetMsg::Request must set `htl: new_htl` (not `htl`) so \
             the decremented value actually propagates on the wire. Window: {window}"
        );
        assert!(
            window.contains("visited: new_visited.clone()"),
            "Forwarded GetMsg::Request must set `visited: new_visited.clone()` \
             so the downstream sees the updated skip set — without this, \
             the downstream could forward back to peers the upstream already \
             tried, forming routing loops. Window: {window}"
        );
        assert!(
            window.contains("id: incoming_tx"),
            "Forwarded GetMsg::Request must reuse `id: incoming_tx` (legacy \
             end-to-end tx preservation). Minting a fresh tx per retry (the \
             original phase-5 implementation) caused downstream to treat each \
             retry as a brand-new Request and spawn a fresh relay subtree, \
             producing 7M spawns in 100s of ci-fault-loss and 63GB RSS."
        );
    }

    /// The `new_visited` bloom filter must be seeded with `own_addr` and
    /// `upstream_addr` BEFORE the retry loop runs, so
    /// `k_closest_potentially_hosting` can't select the upstream (loop) or
    /// this peer (self-forward). Regression risk: if either mark is
    /// missing, routing may loop back immediately.
    #[test]
    fn visited_bloom_seeded_with_own_and_upstream_before_loop() {
        let src = production_source();
        let body = extract_fn_body(src, "async fn drive_relay_get_inner<CB>(");
        let loop_start = body.find("loop {").expect("retry loop must exist");
        let pre_loop = &body[..loop_start];
        assert!(
            pre_loop.contains("new_visited.mark_visited(upstream_addr);"),
            "`new_visited.mark_visited(upstream_addr)` must run BEFORE the \
             retry loop so downstream routing can't immediately hand back \
             to upstream."
        );
        // own_addr is guarded by `if let Some(...)` so check for the mark call.
        assert!(
            pre_loop.contains("new_visited.mark_visited(own_addr);"),
            "`new_visited.mark_visited(own_addr)` must run BEFORE the retry \
             loop so we don't route back to ourselves."
        );
    }

    // ── R12a→R13: send_found failure → compensating NotFound ───────────────

    /// When `relay_send_found` fails (serialization or transport error
    /// surfaced as `OpError::NotificationError`), the `?` propagation in
    /// `drive_relay_get_inner` surfaces the error to `drive_relay_get`,
    /// which must catch it and send a compensating NotFound upstream —
    /// otherwise the upstream waits for the full OPERATION_TTL on an op
    /// the relay has already abandoned.
    #[test]
    fn drive_relay_get_sends_compensating_not_found_on_inner_err() {
        let src = production_source();
        let body = extract_fn_body(src, "async fn drive_relay_get<CB>(");
        // Expected shape:
        //   match drive_relay_get_inner(...).await {
        //     Ok(()) => Ok(()),
        //     Err(err) => {
        //       tracing::warn!(...);
        //       relay_send_not_found(...).await;
        //       Err(err)
        //     }
        //   }
        let err_arm = body
            .find("Err(err) =>")
            .expect("drive_relay_get must have an Err arm");
        let tail = &body[err_arm..];
        assert!(
            tail.contains("relay_send_not_found"),
            "`drive_relay_get` Err arm must call `relay_send_not_found` so \
             that an inner infrastructure error (including `relay_send_found` \
             failures surfaced via `?`) produces a compensating NotFound \
             upstream instead of a silent 60s upstream timeout."
        );
        assert!(
            tail.contains("upstream_addr"),
            "The compensating NotFound in `drive_relay_get` must target \
             `upstream_addr`, not any other peer."
        );
        assert!(
            tail.contains("Err(err)"),
            "`drive_relay_get` Err arm must re-raise `Err(err)` after \
             sending the compensating NotFound, so `run_relay_get`'s \
             infra-error log still fires."
        );
    }

    /// `relay_send_found` must map fire-and-forget send failures to
    /// `OpError::NotificationError` so the `?` in `drive_relay_get_inner`
    /// surfaces them to the outer error funnel. A `?` on an `Ok` unit
    /// type would be a dead propagation; a non-OpError return would
    /// break the error funnel.
    #[test]
    fn relay_send_found_maps_send_failure_to_op_error() {
        let src = production_source();
        let body = extract_fn_body(src, "async fn relay_send_found<CB>(");
        assert!(
            body.contains("map_err(|_| OpError::NotificationError)"),
            "`relay_send_found` must map fire-and-forget send errors to \
             `OpError::NotificationError` so `?` surfaces them to the outer \
             `drive_relay_get` error funnel and triggers the compensating \
             NotFound."
        );
    }

    // ── #4307: Relay streaming-forward regression guards ───────────────────

    /// `relay_send_found` must stream large payloads to a remote upstream
    /// instead of falling back to inline store-and-forward. Regression
    /// guard for #4307 (the task-per-tx migration dropped this producer).
    /// Mirrors PUT's producer pin.
    #[test]
    fn relay_send_found_streams_large_payload_to_remote() {
        let src = production_source();
        let body = extract_fn_body(src, "async fn relay_send_found<CB>(");
        assert!(
            body.contains("should_use_streaming"),
            "`relay_send_found` must gate the remote-upstream path on \
             `should_use_streaming` so large payloads stream (#4307)."
        );
        assert!(
            body.contains("ResponseStreaming"),
            "`relay_send_found` must emit a `GetMsg::ResponseStreaming` \
             metadata header on the streaming branch (#4307)."
        );
        assert!(
            body.contains("conn_manager") && body.contains("send_stream"),
            "`relay_send_found` must call `conn_manager.send_stream(..)` to \
             push raw fragments on the streaming branch (#4307)."
        );
    }

    /// The relay `Terminal::Streaming` arm must FORWARD (send the metadata
    /// header + pipe fragments) BEFORE assembling/caching locally — the
    /// #4155 forward-before-cache invariant applied to the streaming path.
    #[test]
    fn relay_streaming_arm_forwards_before_caching() {
        let src = production_source();
        let body = extract_fn_body(src, "async fn drive_relay_get_inner<CB>(");
        let arm_start = body
            .find("AttemptOutcome::Terminal(Terminal::Streaming {")
            .expect("Streaming arm must exist in relay driver");
        let tail = &body[arm_start..];
        let pipe = tail
            .find("pipe_stream")
            .expect("Streaming arm must call pipe_stream to forward upstream");
        // The forward-path assemble/cache (best-effort local cache after
        // the pipe) are the LAST occurrences in the arm. The loopback
        // safety-net assemble/cache appear earlier but are inside a
        // separate `return Ok(())` branch (upstream == own_addr), so we
        // anchor on the final occurrences to verify the FORWARD path
        // forwards before it caches.
        let assemble = tail
            .rfind(".assemble()")
            .expect("Streaming arm must assemble for local cache");
        let cache = tail
            .rfind("cache_contract_locally")
            .expect("Streaming arm must cache locally");
        assert!(
            pipe < assemble,
            "Streaming arm forward path must `pipe_stream` BEFORE blocking \
             on `handle.assemble()` (forward-before-cache, #4155/#4307)."
        );
        assert!(
            pipe < cache,
            "Streaming arm forward path must forward (pipe_stream) BEFORE \
             `cache_contract_locally` (forward-before-cache, #4155/#4307)."
        );
    }

    /// The relay `Terminal::Streaming` arm must re-key the outbound stream
    /// with a FRESH `StreamId::next_operations()` and `fork()` the inbound
    /// handle so it can both pipe and cache. Never reuse the inbound id.
    #[test]
    fn relay_streaming_arm_uses_fresh_outbound_stream_id() {
        let src = production_source();
        let body = extract_fn_body(src, "async fn drive_relay_get_inner<CB>(");
        let arm_start = body
            .find("AttemptOutcome::Terminal(Terminal::Streaming {")
            .expect("Streaming arm must exist in relay driver");
        let tail = &body[arm_start..];
        let clip = tail[1..]
            .find("AttemptOutcome::")
            .map(|p| p + 1)
            .unwrap_or(tail.len());
        let arm = &tail[..clip];
        assert!(
            arm.contains("let outbound_sid = StreamId::next_operations()"),
            "Streaming arm must mint a fresh outbound stream id via \
             `let outbound_sid = StreamId::next_operations()` per hop (#4307)."
        );
        assert!(
            arm.contains(".fork()"),
            "Streaming arm must `fork()` the inbound handle so it can pipe \
             AND assemble for local cache (#4307)."
        );
        // The fresh `outbound_sid` (NOT the inbound `stream_id`) must be the
        // one re-keyed into the forwarded header AND piped. Without these the
        // arm could mint `outbound_sid` yet still pipe/advertise the inbound
        // id — exactly the re-keying bug this pin guards against.
        assert!(
            arm.contains("stream_id: outbound_sid"),
            "Streaming arm must re-key the forwarded `ResponseStreaming` \
             header with the FRESH `outbound_sid` (`stream_id: outbound_sid`), \
             not the inbound `stream_id` (#4307)."
        );
        assert!(
            arm.contains(".pipe_stream(upstream_addr, outbound_sid"),
            "Streaming arm must pipe the forked handle under the FRESH \
             `outbound_sid` (`pipe_stream(upstream_addr, outbound_sid, ..)`), \
             not the inbound `stream_id` (#4307)."
        );
    }

    /// Pin the deliberate non-`?` handling of a `pipe_stream` failure in the
    /// relay `Terminal::Streaming` arm. Once the `ResponseStreaming` header
    /// has gone upstream, the upstream is committed to assembling a stream;
    /// propagating the pipe error would bubble to `drive_relay_get` and send
    /// a compensating `Response{NotFound}` to that SAME upstream — a
    /// contradictory double-signal that stalls it ~60s on `claim_or_wait`.
    /// The arm therefore logs and `return Ok(())` instead. This invariant is
    /// hard to exercise behaviourally (the mock bridge's `pipe_stream` can't
    /// fail), so pin the SHAPE: a future refactor flipping `return Ok(())`
    /// to `?`/`return Err(..)`/a NotFound send here would silently regress.
    #[test]
    fn relay_streaming_arm_pipe_failure_returns_ok_without_notfound() {
        let src = production_source();
        let body = extract_fn_body(src, "async fn drive_relay_get_inner<CB>(");
        let arm_start = body
            .find("AttemptOutcome::Terminal(Terminal::Streaming {")
            .expect("Streaming arm must exist in relay driver");
        let tail = &body[arm_start..];
        let clip = tail[1..]
            .find("AttemptOutcome::")
            .map(|p| p + 1)
            .unwrap_or(tail.len());
        let arm = &tail[..clip];

        // Isolate the `if let Err(e) = conn_manager.pipe_stream(..) { .. }`
        // block: from the `pipe_stream` call to the end of the arm.
        let pipe_pos = arm
            .find(".pipe_stream(upstream_addr, outbound_sid")
            .expect("Streaming arm must call pipe_stream on the forward path");
        let pipe_tail = &arm[pipe_pos..];
        // The error-handling block runs until Step 4 (route-event recording).
        let block_end = pipe_tail
            .find("record_relay_route_event")
            .expect("route-event recording must follow the pipe on success");
        let err_block = &pipe_tail[..block_end];

        assert!(
            err_block.contains("if let Err(e) = conn_manager")
                || arm[..pipe_pos].contains("if let Err(e) = conn_manager"),
            "pipe_stream must be guarded by an `if let Err(e) = ..` block, \
             not `?`-propagated (the header already went upstream)."
        );
        assert!(
            err_block.contains("return Ok(())"),
            "On `pipe_stream` failure AFTER the header was sent upstream, the \
             streaming arm MUST `return Ok(())` (let the upstream's claim time \
             out cleanly), NOT propagate the error — a propagated error makes \
             `drive_relay_get` send a contradictory `Response{{NotFound}}` to \
             the same upstream and stalls it ~60s. #4307."
        );
        assert!(
            !err_block.contains("relay_send_not_found"),
            "The `pipe_stream`-failure block must NOT send a NotFound \
             upstream — the upstream is already committed to a stream."
        );
    }

    // ── R12b (SUPERSEDED): streaming-downstream WARN+continue guard ────────

    /// SUPERSEDED by #4307: relay streaming-forward IS now implemented (the
    /// `Terminal::Streaming` arm forks + pipes the stream upstream), so the
    /// WARN+skip invariant this test pinned no longer holds. Kept as
    /// historical documentation per `git-workflow.md` ("superseded by a
    /// semantic change → add `#[ignore]`, keep as historical documentation").
    /// The behaviour it used to assert is now inverted and pinned by
    /// `relay_send_found_streams_large_payload_to_remote`,
    /// `relay_streaming_arm_forwards_before_caching`,
    /// `relay_streaming_arm_uses_fresh_outbound_stream_id`, and
    /// `relay_streaming_arm_pipe_failure_returns_ok_without_notfound`. This
    /// test references the pre-#4307 non-generic `drive_relay_get_inner`
    /// signature and the old WARN+skip arm on purpose — it is a snapshot of
    /// the prior contract, not a live guard, and is never executed.
    #[test]
    #[ignore = "superseded: relay streaming forwarding now implemented (#4307); kept as historical documentation per git-workflow.md"]
    fn streaming_downstream_is_currently_warned_and_skipped() {
        let src = production_source();
        let body = extract_fn_body(src, "async fn drive_relay_get_inner(");
        let streaming_arm_start = body
            .find("AttemptOutcome::Terminal(Terminal::Streaming { .. })")
            .expect("Streaming arm must exist in relay driver");
        let tail = &body[streaming_arm_start..];
        // Bound at the next arm start.
        let clip = tail[1..]
            .find("AttemptOutcome::")
            .map(|p| p + 1)
            .unwrap_or(tail.len());
        let arm = &tail[..clip];
        assert!(
            arm.contains("continue;"),
            "Streaming arm must `continue;` to try the next peer — streaming \
             relay forwarding is out of scope for #3883 (see port plan §7). \
             A future PR will replace this with a proper chunk pipe-through."
        );
        assert!(
            arm.contains("new_visited.mark_visited(peer_addr)"),
            "Streaming arm must mark the streaming peer as visited so the \
             retry loop doesn't re-select it next iteration."
        );
        assert!(
            !arm.contains("relay_send_found"),
            "Streaming arm must NOT call `relay_send_found` — doing so \
             without the chunk payload would send a Found frame with \
             `state: None` (Unexpected at the upstream classify). See R12b \
             gap in port plan risk register."
        );
        assert!(
            !arm.contains("orphan_stream_registry"),
            "Streaming arm must NOT claim the stream via \
             `orphan_stream_registry` — that's the migrated behavior for a \
             follow-up PR. Doing it here without the upstream pipe would \
             leak stream state."
        );
    }

    // ── R9: send_and_await Err/timeout outcomes advance to next peer ───────

    /// Both `Ok(Err(..))` (channel error / event loop gone) and
    /// `Err(Elapsed)` (timeout) arms of the `tokio::time::timeout` wrapper
    /// must:
    ///   - mark the failed peer with `new_visited.mark_visited(peer_addr)`
    ///   - `continue` to the next loop iteration
    ///
    /// A regression where either arm `break`s or `return Err(...)`s would
    /// abandon remaining candidates and send a premature NotFound.
    #[test]
    fn send_and_await_failure_arms_continue_to_next_peer() {
        let src = production_source();
        let body = extract_fn_body(src, "async fn drive_relay_get_inner<CB>(");
        // Match on the outer `round_trip` match arms.
        let round_trip = body
            .find("let reply = match round_trip {")
            .expect("round_trip match must exist");
        let tail = &body[round_trip..];
        // Clip at the end of the match (next `match classify(reply)`).
        let clip = tail
            .find("match classify(reply)")
            .expect("classify match must follow round_trip match");
        let match_body = &tail[..clip];
        // Channel-error arm: `Ok(Err(err)) => { ... continue; }`.
        let err_arm = match_body
            .find("Ok(Err(err)) =>")
            .expect("channel-error arm must exist");
        let err_tail = &match_body[err_arm..];
        let err_arm_end = err_tail
            .find("Err(_elapsed) =>")
            .expect("timeout arm must follow channel-error arm");
        let err_block = &err_tail[..err_arm_end];
        assert!(
            err_block.contains("continue;"),
            "`Ok(Err(_))` arm must `continue;` so the loop tries the next \
             peer. A regression that returns or breaks here would abandon \
             remaining candidates."
        );
        assert!(
            err_block.contains("mark_visited(peer_addr)"),
            "`Ok(Err(_))` arm must mark the failing peer as visited so the \
             next `relay_advance_to_next_peer` call doesn't re-select it."
        );
        // Timeout arm.
        let timeout_arm = match_body
            .find("Err(_elapsed) =>")
            .expect("timeout arm must exist");
        let timeout_tail = &match_body[timeout_arm..];
        // Clip at the end of the match block.
        let timeout_end = timeout_tail.rfind("};").unwrap_or(timeout_tail.len());
        let timeout_block = &timeout_tail[..timeout_end];
        assert!(
            timeout_block.contains("continue;"),
            "`Err(_elapsed)` (timeout) arm must `continue;` so the loop \
             tries the next peer. A regression that returns here would \
             mean any slow peer permanently blocks the relay."
        );
        assert!(
            timeout_block.contains("mark_visited(peer_addr)"),
            "`Err(_elapsed)` (timeout) arm must mark the timing-out peer \
             as visited; otherwise the retry loop might re-select it and \
             time out again."
        );
    }

    // ── Per-tx independence pin ───────────────────────────────────────────
    //
    // Per-tx independence is enforced by `active_relay_get_txs` —
    // `start_relay_get` rejects a duplicate inbound Request whose
    // `incoming_tx` already has a live driver via the
    // `Relay*InflightGuard` RAII pattern. Dedup is keyed on
    // transaction id (NOT contract instance id), so two concurrent
    // relay GETs for the *same* contract from different upstreams each
    // get their own driver task and their own upstream reply.
    #[test]
    fn relay_inflight_dedup_is_per_transaction_not_per_contract() {
        const SRC: &str = include_str!("../get/op_ctx_task.rs");
        let guard_start = SRC
            .find("RelayGetInflightGuard")
            .expect("RelayGetInflightGuard must exist");
        let window = &SRC[guard_start..(guard_start + 4000).min(SRC.len())];
        assert!(
            window.contains("active_relay_get_txs"),
            "Relay GET inflight dedup must use `active_relay_get_txs` \
             (per-transaction DashSet)."
        );
        // Compose the negative-match needles at runtime so this test's
        // own source doesn't match against `include_str!`.
        let per_key_needle_a = format!("active_relay_get_{}", "keys");
        let per_key_needle_b = format!("active_relay_get_{}", "instance_ids");
        assert!(
            !window.contains(&per_key_needle_a) && !window.contains(&per_key_needle_b),
            "Inflight dedup must NOT key on contract instance id; per-key \
             dedup would break the upstream-reply invariant."
        );
    }

    /// Pin: `run_relay_get` MUST skip `release_pending_op_slot` when
    /// running in originator-loopback mode (`upstream_addr ==
    /// own_addr`). The `pending_op_results` callback for `incoming_tx`
    /// in that mode is the originator's `send_and_await` waiter, not
    /// one this driver installed; releasing it would emit
    /// `TransactionCompleted` and remove the originator's callback
    /// BEFORE the loopback `GetMsg::Response` reaches the bypass
    /// (notifications channel has higher priority than op_execution
    /// in priority_select). Repro:
    /// `test_get_notfound_no_forwarding_targets`.
    #[test]
    fn run_relay_get_skips_release_in_originator_loopback() {
        let src = include_str!("../get/op_ctx_task.rs");
        let fn_start = src
            .find("async fn run_relay_get<CB>(")
            .expect("run_relay_get not found");
        // Bound the search window: `drive_relay_get` follows
        // `run_relay_get` in source order, gated by the
        // `clippy::too_many_arguments` attr.
        let fn_end = src[fn_start..]
            .find("\n#[allow(clippy::too_many_arguments)]\nasync fn drive_relay_get<CB>(")
            .expect("end-of-run_relay_get marker not found")
            + fn_start;
        let body = &src[fn_start..fn_end];
        // The release call must be guarded by an own_addr comparison.
        let release_pos = body
            .find("release_pending_op_slot(incoming_tx)")
            .expect("release_pending_op_slot call not found in run_relay_get");
        let preceding = &body[..release_pos];
        assert!(
            preceding.rfind("get_own_addr()").is_some(),
            "run_relay_get must call get_own_addr() before \
             release_pending_op_slot to gate the release on the \
             upstream != own_addr case"
        );
        assert!(
            preceding.rfind("!originator_loopback").is_some(),
            "run_relay_get must guard release_pending_op_slot with the \
             `!originator_loopback` check (originator-loopback exception)"
        );
        assert!(
            body.contains("originator_loopback"),
            "run_relay_get must compute originator_loopback to gate the \
             release path"
        );
    }

    /// Pin: `relay_send_not_found` and `relay_send_found` MUST use
    /// `send_local_loopback` when `upstream_addr == own_addr`.
    /// Sending wire-bound `send_fire_and_forget(own_addr, ...)` would
    /// attempt a UDP self-connection that has no peer entry, failing
    /// silently. Routing as `InboundMessage` via `send_local_loopback`
    /// lands at the bypass in `handle_pure_network_message_v1` and
    /// forwards to the originator's `pending_op_results` waiter.
    #[test]
    fn relay_send_responses_use_local_loopback_on_own_addr() {
        let src = include_str!("../get/op_ctx_task.rs");
        for fn_name in [
            "async fn relay_send_not_found(",
            "async fn relay_send_found<CB>(",
        ] {
            let fn_start = src
                .find(fn_name)
                .unwrap_or_else(|| panic!("{fn_name} not found"));
            // Bound the search at the next async fn declaration.
            let fn_end = src[fn_start + fn_name.len()..]
                .find("\nasync fn ")
                .map(|idx| idx + fn_start + fn_name.len())
                .unwrap_or(src.len());
            let body = &src[fn_start..fn_end];
            assert!(
                body.contains("send_local_loopback("),
                "{fn_name} must call send_local_loopback for \
                 upstream==own_addr (originator-loopback path)"
            );
            assert!(
                body.contains("get_own_addr()"),
                "{fn_name} must compare upstream_addr to \
                 connection_manager.get_own_addr() to detect loopback"
            );
        }
    }

    /// Pin: `drive_relay_get_inner`'s retry loop MUST switch to
    /// `send_fire_and_forget` (no waiter install) when the relay
    /// driver runs in originator-loopback. `send_to_and_await`
    /// would `state.pending_op_results.insert(*tx, callback)`,
    /// silently OVERWRITING the originator's `start_client_get`
    /// waiter (`incoming_tx == client_tx` in loopback). The peer's
    /// downstream Response would then land in the relay-driver's
    /// callback and never reach the client driver. After loopback
    /// dispatch, the driver returns immediately so the client
    /// driver's still-installed callback receives the Response via
    /// the bypass and owns retry semantics. Mirrors
    /// `drive_relay_put`'s originator-loopback branch.
    #[test]
    fn drive_relay_get_loopback_uses_fire_and_forget() {
        let src = include_str!("../get/op_ctx_task.rs");
        let fn_start = src
            .find("async fn drive_relay_get_inner<CB>(")
            .expect("drive_relay_get_inner not found");
        let fn_end = src[fn_start + "async fn drive_relay_get_inner<CB>(".len()..]
            .find("\nasync fn ")
            .map(|idx| idx + fn_start + "async fn drive_relay_get_inner<CB>(".len())
            .unwrap_or(src.len());
        let body = &src[fn_start..fn_end];
        assert!(
            body.contains("originator_loopback"),
            "drive_relay_get_inner must compute originator_loopback \
             in the retry loop to gate the waiter-install branch"
        );
        // `send_fire_and_forget(peer_addr` must appear in the loopback
        // branch (compose at runtime so this test's own source doesn't
        // match the negative-grep).
        let needle = format!("send_fire_and_{}(peer_addr,", "forget");
        assert!(
            body.contains(&needle),
            "drive_relay_get_inner loopback branch must use \
             send_fire_and_forget(peer_addr, ...) to avoid overwriting \
             the originator's pending_op_results waiter"
        );
    }

    // ── C1: cache_contract_locally must gate mark_local_client_access ──────

    /// Regression guard for the relay hosting-cache taint bug caught in
    /// PR #3896 review. The legacy GET branch gates `mark_local_client_access`
    /// on `is_original_requester = upstream_addr.is_none()` (see
    /// `get.rs:2260-2262, :2353-2355, :3056-3058`). The driver
    /// MUST respect that gate: relay peers that merely cache a forwarded
    /// Found must NOT set the sticky `local_client_access` flag, or they
    /// permanently pay subscription-renewal cost for contracts no client
    /// on the relay node ever asked for.
    ///
    /// Source-scrape invariant: `cache_contract_locally` must accept an
    /// `is_client_requester: bool` parameter and gate the
    /// `mark_local_client_access` call on it.
    #[test]
    fn cache_contract_locally_gates_mark_local_client_access_on_requester() {
        let src = production_source();
        // Function signature must carry the new parameter.
        let sig_start = src
            .find("async fn cache_contract_locally(")
            .expect("cache_contract_locally must exist");
        let sig_window = &src[sig_start..(sig_start + 400).min(src.len())];
        assert!(
            sig_window.contains("is_client_requester: bool"),
            "`cache_contract_locally` must accept `is_client_requester: bool` \
             so relay callsites can opt out of the sticky local_client_access \
             flag. Sig window: {sig_window}"
        );
        // Body must gate `mark_local_client_access` on the flag.
        let body = extract_fn_body(src, "async fn cache_contract_locally(");
        let gate_pos = body
            .find("if is_client_requester {")
            .expect("mark_local_client_access must be gated on is_client_requester");
        let mark_pos = body
            .find("mark_local_client_access")
            .expect("mark_local_client_access must still be called under the gate");
        assert!(
            gate_pos < mark_pos,
            "`if is_client_requester {{` must precede the \
             `mark_local_client_access` call; otherwise the gate is \
             structurally useless."
        );
        // Negative check: there must be NO unconditional (unguarded) call.
        let guarded_snippet =
            "if is_client_requester {\n        op_manager.ring.mark_local_client_access";
        assert!(
            body.contains(guarded_snippet),
            "The `mark_local_client_access` call must be directly inside the \
             `if is_client_requester {{ ... }}` block. Current body structure \
             may have split the guard from the call.\n{body}"
        );
    }

    /// All relay-driver cache callsites must pass `false`.
    /// Relay caches forwarded Found payloads but MUST NOT flag them as
    /// client-accessed on the relay's own hosting cache. There are five
    /// relay cache callsites in `drive_relay_get_inner`:
    ///   1. Active-interest local Found (R4, immediate serve)
    ///   2. Exhaustion fallback (R10, stale local state)
    ///   3. Downstream Found bubble-up (R12a, forwarded payload)
    ///   4. Streaming loopback safety-net (#4307, upstream == own_addr)
    ///   5. Streaming forward best-effort cache (#4307, after pipe_stream)
    #[test]
    fn all_relay_callsites_pass_is_client_requester_false() {
        let src = production_source();
        let body = extract_fn_body(src, "async fn drive_relay_get_inner<CB>(");
        let callsites: Vec<usize> = body
            .match_indices("cache_contract_locally(")
            .map(|(i, _)| i)
            .collect();
        assert_eq!(
            callsites.len(),
            5,
            "drive_relay_get_inner should have exactly five \
             cache_contract_locally callsites (R4 immediate, R10 fallback, \
             R12a bubble-up, plus the two #4307 streaming-arm caches). \
             Found {} — a refactor has changed the shape.",
            callsites.len(),
        );
        // Each callsite must terminate with `, false)` (the
        // `is_client_requester` argument). The body contains non-ASCII
        // comment decorations, so walk by char rather than by byte to avoid
        // slicing on a multi-byte boundary.
        for (idx, &pos) in callsites.iter().enumerate() {
            let tail = &body[pos..];
            // End-of-args: first matching closing `)` at depth 0.
            let mut depth: i32 = 0;
            let mut end: Option<usize> = None;
            for (i, c) in tail.char_indices() {
                match c {
                    '(' => depth += 1,
                    ')' => {
                        depth -= 1;
                        if depth == 0 {
                            end = Some(i);
                            break;
                        }
                    }
                    _ => {}
                }
            }
            let end = end.unwrap_or_else(|| {
                panic!("unterminated cache_contract_locally call at relay callsite #{idx}")
            });
            let call = &tail[..=end];
            // The last argument must be `false`. Normalize whitespace.
            let normalized: String = call.chars().filter(|c| !c.is_whitespace()).collect();
            assert!(
                normalized.ends_with("false,).await")
                    || normalized.ends_with("false)")
                    || normalized.ends_with("false,)"),
                "Relay callsite #{idx} of cache_contract_locally must pass \
                 `false` for is_client_requester (relay is not the client). \
                 Call text: {call}"
            );
        }
    }

    /// The `client_driver`-side callsite (drive_client_get_inner's
    /// InlineFound arm) must pass `true`. Streaming assembly
    /// (`assemble_and_cache_stream`) also must pass `true` — the stream
    /// is only claimed by the client driver.
    #[test]
    fn client_driver_and_streaming_callsites_pass_is_client_requester_true() {
        let src = production_source();
        // Client driver InlineFound arm.
        let drive_body = extract_fn_body(src, "async fn drive_client_get_inner(");
        let drive_call_pos = drive_body
            .find("cache_contract_locally(")
            .expect("client driver must cache_contract_locally on InlineFound");
        let drive_window =
            &drive_body[drive_call_pos..(drive_call_pos + 400).min(drive_body.len())];
        let drive_normalized: String = drive_window
            .chars()
            .take_while(|&c| c != ';')
            .filter(|c| !c.is_whitespace())
            .collect();
        assert!(
            drive_normalized.contains("true"),
            "Client driver's cache_contract_locally call must pass `true` for \
             is_client_requester (this node initiated the GET). Call window: \
             {drive_window}"
        );
        // Streaming assembly.
        let stream_body = extract_fn_body(src, "async fn assemble_and_cache_stream(");
        let stream_call_pos = stream_body
            .find("cache_contract_locally(")
            .expect("assemble_and_cache_stream must cache_contract_locally");
        let stream_window =
            &stream_body[stream_call_pos..(stream_call_pos + 400).min(stream_body.len())];
        let stream_normalized: String = stream_window
            .chars()
            .take_while(|&c| c != ';')
            .filter(|c| !c.is_whitespace())
            .collect();
        assert!(
            stream_normalized.contains("true"),
            "assemble_and_cache_stream must pass `true` for is_client_requester \
             (stream is only claimed by the client-originating driver). Call \
             window: {stream_window}"
        );
    }

    /// Docstring-level guard: the legacy-mirror references in
    /// `cache_contract_locally`'s docstring (`get.rs:2260-2262, :2353-2355,
    /// :3056-3058`) name the three legacy sites where the
    /// `is_original_requester` gate lives. If those line numbers ever stop
    /// referring to `mark_local_client_access` call sites, the docstring
    /// has rotted and future maintenance may miss the invariant.
    ///
    /// This test anchors on the function-name reference rather than the
    /// line numbers themselves (line numbers drift on unrelated edits) —
    /// it just verifies the docstring still cites the function by name so
    /// readers can grep for it.
    #[test]
    fn cache_contract_locally_docstring_cites_legacy_mirror() {
        let src = production_source();
        let fn_pos = src
            .find("async fn cache_contract_locally(")
            .expect("cache_contract_locally must exist");
        // Look in the 1500 chars before the fn for the docstring.
        let window_start = fn_pos.saturating_sub(1500);
        let window = &src[window_start..fn_pos];
        assert!(
            window.contains("is_client_requester"),
            "cache_contract_locally docstring must describe the \
             is_client_requester parameter so callers know which value to pass."
        );
        assert!(
            window.contains("mark_local_client_access"),
            "cache_contract_locally docstring must name the legacy call \
             (`mark_local_client_access`) it gates on is_client_requester."
        );
    }

    // ── Counter: relay driver call count is wired ──────────────────────────

    /// The `RELAY_DRIVER_CALL_COUNT` test counter must be incremented at
    /// the top of `start_relay_get` under `#[cfg(any(test, feature =
    /// "testing"))]`. Behavioral tests use this to assert the dispatch
    /// gate routed a fresh inbound Request through the driver rather
    /// than through the legacy fallthrough.
    #[test]
    fn relay_driver_call_count_incremented_on_entry() {
        let src = production_source();
        // Counter declaration must exist.
        assert!(
            src.contains("pub static RELAY_DRIVER_CALL_COUNT"),
            "RELAY_DRIVER_CALL_COUNT static must be declared for behavioral \
             tests to verify the dispatch gate routes through the relay driver."
        );
        // Increment must appear in the body of start_relay_get, under cfg.
        let body = extract_fn_body(src, "pub(crate) async fn start_relay_get<CB>(");
        assert!(
            body.contains("RELAY_DRIVER_CALL_COUNT.fetch_add(1"),
            "`start_relay_get` must increment `RELAY_DRIVER_CALL_COUNT` at \
             entry so integration tests can assert dispatch-gate coverage."
        );
        // The increment must be cfg-gated to avoid shipping test code.
        let counter_pos = body.find("RELAY_DRIVER_CALL_COUNT.fetch_add").unwrap();
        // Walk back ~200 chars for the cfg attribute.
        let pre = &body[counter_pos.saturating_sub(200)..counter_pos];
        assert!(
            pre.contains("#[cfg(any(test, feature = \"testing\"))]"),
            "`RELAY_DRIVER_CALL_COUNT` increment must be gated behind \
             `#[cfg(any(test, feature = \"testing\"))]` so it doesn't ship \
             in release builds."
        );
    }

    /// Pin: `start_sub_op_get` MUST exist as the sub-op GET entry
    /// point. Removing it would force legacy `get::start_op` +
    /// `request_get` revival.
    #[test]
    fn start_sub_op_get_entry_must_exist() {
        let src = include_str!("op_ctx_task.rs");
        let needle = "pub(crate) fn start_sub_op_get(";
        assert!(
            src.contains(needle),
            "start_sub_op_get fn must remain — sub-op GET migration entry point"
        );
    }

    /// Pin: sub-op driver MUST NOT auto-subscribe or hand off to a
    /// child SUBSCRIBE. The caller (executor's
    /// `local_state_or_from_network` or subscribe's
    /// `fetch_contract_if_missing`) drives those side effects when
    /// appropriate. Doubling them up risks duplicate SUBSCRIBE op
    /// dispatch.
    #[test]
    fn sub_op_driver_skips_auto_subscribe_and_maybe_subscribe_child() {
        let src = include_str!("op_ctx_task.rs");
        // Boundary `\n}\n\n/// Cause` matches the literal closing brace
        // of `drive_sub_op_get` followed by the docstring of the
        // immediately-following `missing_state_cause` helper. This
        // anchors the pin to the function body proper, not the helpers
        // and comment blocks that follow.
        let body = src
            .split("async fn drive_sub_op_get(")
            .nth(1)
            .expect("drive_sub_op_get must exist")
            .split("\n}\n\n/// Cause")
            .next()
            .expect("end of drive_sub_op_get body");
        assert!(
            !body.contains("auto_subscribe_on_get_response"),
            "drive_sub_op_get must NOT call auto_subscribe_on_get_response — \
             sub-op caller owns subscribe semantics"
        );
        assert!(
            !body.contains("maybe_subscribe_child"),
            "drive_sub_op_get must NOT call maybe_subscribe_child — \
             sub-op caller owns subscribe semantics"
        );
        assert!(
            !body.contains("send_client_result"),
            "drive_sub_op_get must NOT publish to result_router via \
             send_client_result — sub-op tx has no client waiter"
        );
    }

    // ── Behavioral coverage for sub-op outcome variants ───────────────────

    /// `start_sub_op_get` must return a tx that is NOT a sub-operation
    /// in the structural sense (no `parent` field) — sub-op GETs are
    /// node-internal but flat in the transaction-tree sense, mirroring
    /// the legacy `request_get` path which used `Transaction::new::<>`.
    /// Regression: if a sub-op tx grew a parent, `is_sub_operation()`
    /// would suppress the legacy `cb.response()` callback path that any
    /// future migration might still rely on.
    #[test]
    fn sub_op_tx_has_no_parent() {
        let tx = crate::message::Transaction::new::<super::GetMsg>();
        assert!(
            !tx.is_sub_operation(),
            "sub-op GET tx must be flat (no parent) — matches legacy \
             request_get + start_op shape"
        );
    }

    /// Behavioral guard: missing-state cause string MUST contain the
    /// instance_id so operators can correlate the warning to a contract.
    /// This is the message surfaced by `SubOpGetOutcome::NotFound` when
    /// the wire layer returned Found but the local store re-query
    /// produced no state — a real failure mode (e.g., contract handler
    /// rejected the PutQuery, or the store was wiped between Response
    /// and re-query).
    #[test]
    fn missing_state_cause_includes_instance_id() {
        use freenet_stdlib::prelude::ContractInstanceId;
        let id = ContractInstanceId::new([0xAB; 32]);
        let cause = super::missing_state_cause(&id);
        assert!(
            cause.contains(&id.to_string()),
            "missing_state_cause must reference the instance_id; got {cause:?}"
        );
        assert!(
            cause.contains("local store"),
            "missing_state_cause must mention local store re-query failure; got {cause:?}"
        );
    }

    /// Behavioral guard: the fire-and-forget caller (subscribe's
    /// `fetch_contract_if_missing`) drops the oneshot receiver
    /// immediately. The driver task's `out_tx.send(outcome)` MUST NOT
    /// panic in that case — the `let _ =` pattern guarantees graceful
    /// receiver-dropped handling. This test exercises the oneshot
    /// shape independently of the driver to lock in that contract.
    #[test]
    fn oneshot_send_after_receiver_drop_is_silent() {
        let (tx, rx) = tokio::sync::oneshot::channel::<super::SubOpGetOutcome>();
        drop(rx);
        // Mirrors the `let _ = out_tx.send(outcome)` pattern in run_sub_op_get.
        // Should return Err(value) without panicking.
        let result = tx.send(super::SubOpGetOutcome::Infra(
            crate::operations::OpError::UnexpectedOpState,
        ));
        assert!(
            result.is_err(),
            "send after receiver drop must return Err, not panic"
        );
    }

    /// Behavioral guard: `SubOpGetOutcome` discriminates the three
    /// distinct delivery cases. Pattern-matching exhaustiveness is
    /// already enforced by the compiler at the executor consumer site
    /// (`local_state_or_from_network`); this test locks in the
    /// constructor shape so future variant additions trip the test.
    #[test]
    fn sub_op_outcome_variants_constructible() {
        use freenet_stdlib::prelude::WrappedState;

        let state = WrappedState::from(vec![1u8, 2, 3]);
        let found =
            super::SubOpGetOutcome::Found(crate::operations::get::GetResult::new(state, None));
        let not_found = super::SubOpGetOutcome::NotFound("exhausted".to_string());
        let infra = super::SubOpGetOutcome::Infra(crate::operations::OpError::UnexpectedOpState);

        assert!(matches!(found, super::SubOpGetOutcome::Found(_)));
        assert!(matches!(not_found, super::SubOpGetOutcome::NotFound(_)));
        assert!(matches!(infra, super::SubOpGetOutcome::Infra(_)));
    }

    /// Pin: each transport-level failure arm of `drive_relay_get_inner`
    /// records a routing event for the failing peer. Without these
    /// hooks, the per-peer dashboard's failure-probability model is
    /// trained only on originated ops and the symptom this PR fixes
    /// reappears for the relay path. Source-scrape because the
    /// behaviour is positional inside the retry loop and a deletion
    /// would not break any unit-test assertion otherwise.
    #[test]
    fn drive_relay_get_inner_records_route_events_on_transport_failure() {
        let src = include_str!("op_ctx_task.rs");
        let body = extract_fn_body(src, "async fn drive_relay_get_inner<CB>(");

        // The send_to_and_await error arm and the timeout arm must
        // record `Failure` for the chosen peer. Identify each by its
        // log-message phrase, then check the arm's body up to the
        // `continue` for the helper call.
        for log_phrase in [
            "send_to_and_await failed; advancing to next peer",
            "attempt timed out; advancing to next peer",
            // #4307: a downstream that advertised a ResponseStreaming header
            // but never delivered an assemblable stream is also a routing
            // failure for that peer — same training as the transport arms.
            "orphan stream claim failed; advancing to next peer",
        ] {
            let pos = body.unwrap_or_default_pos(log_phrase);
            let after = &body[pos..pos + 1500.min(body.len() - pos)];
            assert!(
                after.contains("record_relay_route_event")
                    && after.contains("RouteOutcome::Failure"),
                "drive_relay_get_inner arm for `{log_phrase}` must call \
                 record_relay_route_event with RouteOutcome::Failure. \
                 Without this, transport failures from relay-forwarded \
                 GETs are dropped and the per-peer failure-probability \
                 model regresses to the originator-only state that \
                 motivated PR #4051."
            );
        }

        // The InlineFound success arm must record SuccessUntimed.
        let pos = body.unwrap_or_default_pos("downstream returned Found");
        let after = &body[pos..pos + 1500.min(body.len() - pos)];
        assert!(
            after.contains("record_relay_route_event")
                && after.contains("RouteOutcome::SuccessUntimed"),
            "drive_relay_get_inner InlineFound arm must call \
             record_relay_route_event with RouteOutcome::SuccessUntimed."
        );

        // The Retry/NotFound arm must record SuccessUntimed too — see
        // the outcome-attribution rationale in operations.rs::record_relay_route_event
        // rustdoc. A peer answering NotFound has not failed.
        let pos = body.unwrap_or_default_pos("downstream returned NotFound; advancing");
        let after = &body[pos..pos + 1500.min(body.len() - pos)];
        assert!(
            after.contains("record_relay_route_event")
                && after.contains("RouteOutcome::SuccessUntimed"),
            "drive_relay_get_inner Retry (NotFound) arm must call \
             record_relay_route_event with RouteOutcome::SuccessUntimed \
             (NotFound is a correct protocol response, not a routing \
             failure). Recording it as Failure would systematically \
             de-prioritise peers that don't host the queried contract."
        );
    }

    /// Regression for #4066: the originator's first
    /// `send_and_await(target=None)` loops back as an InboundMessage
    /// with `source_addr=None`, which falls through to legacy
    /// `process_message` (the relay-driver dispatch is gated on
    /// `source_addr.is_some()`) and pushes a `GetOp` into
    /// `OpManager.ops.get` keyed by `client_tx`. If the driver task
    /// exits without `op_manager.completed()` having been called for
    /// `client_tx`, the legacy entry lingers until the periodic GC
    /// sweep at OPERATION_TTL=60s (which races the driver's
    /// per-attempt timeout, also 60s) and emits a misleading
    /// `phase=get_timeout` log + duplicate `OperationError` to the
    /// client.
    ///
    /// Implemented via an RAII guard installed at the top of
    /// `run_client_get` so cleanup runs on every exit path —
    /// including a panic inside the driver loop, which the previous
    /// per-arm `completed()` calls did not cover (skeptical-reviewer
    /// callout on PR #4070, "panic / abort path still leaks").
    /// Pin both the guard installation and the Drop impl that clears
    /// the legacy entry.
    #[test]
    fn run_client_get_installs_completion_guard() {
        let src = production_source();
        let body = extract_fn_body(src, "async fn run_client_get(");
        assert!(
            body.contains("ClientGetCompletionGuard {"),
            "run_client_get must install a ClientGetCompletionGuard so the \
             legacy ops.get entry created by the originator-loopback Request \
             is cleared on every exit path including a driver panic (#4066). \
             Per-arm completed() calls in drive_client_get_inner are NOT \
             enough — a panic inside drive_retry_loop or any of its awaits \
             aborts the task before reaching the match block, leaving the \
             entry to be reaped by the GC sweep that emits phantom \
             phase=get_timeout."
        );
        assert!(
            body.contains("let _completion_guard = ClientGetCompletionGuard"),
            "ClientGetCompletionGuard must be bound to a guard binding \
             (`let _completion_guard = ...`) so it lives for the full \
             function scope. A bare `let _ = ...` would drop it immediately."
        );

        // The guard's Drop must call op_manager.completed.
        let drop_impl = src
            .split("impl Drop for ClientGetCompletionGuard")
            .nth(1)
            .expect("ClientGetCompletionGuard must have an explicit Drop impl");
        let drop_body = drop_impl
            .split("fn drop")
            .nth(1)
            .expect("ClientGetCompletionGuard Drop impl must define fn drop");
        // Bound the search to the body of fn drop — the next `}` after
        // the opening `{` belongs to the inner block; we just need to
        // confirm `completed(` appears somewhere inside the impl block.
        assert!(
            drop_body.contains(".completed(self.client_tx)"),
            "ClientGetCompletionGuard::drop must call \
             op_manager.completed(self.client_tx) — see #4066"
        );
    }

    /// Same invariant for the sub-op driver: callers (executor's
    /// `local_state_or_from_network`, subscribe's
    /// `fetch_contract_if_missing`) feed the sub-op outcome into their
    /// own logic, but the originator-loopback path that creates the
    /// legacy `ops.get` entry runs on the SAME node, keyed by the
    /// sub-op `tx`. Without the guard, the sub-op's caller observes a
    /// clean failure but the node still emits `phase=get_timeout` 60s
    /// later for the orphaned entry.
    #[test]
    fn run_sub_op_get_installs_completion_guard() {
        let src = production_source();
        let body = extract_fn_body(src, "async fn run_sub_op_get(");
        assert!(
            body.contains("SubOpGetCompletionGuard {"),
            "run_sub_op_get must install a SubOpGetCompletionGuard so the \
             legacy ops.get entry created by the originator-loopback Request \
             is cleared on every exit path — see \
             run_client_get_installs_completion_guard for the failure mode \
             (#4066)"
        );
        assert!(
            body.contains("let _completion_guard = SubOpGetCompletionGuard"),
            "SubOpGetCompletionGuard must be bound to a guard binding so it \
             lives for the full function scope"
        );

        let drop_impl = src
            .split("impl Drop for SubOpGetCompletionGuard")
            .nth(1)
            .expect("SubOpGetCompletionGuard must have an explicit Drop impl");
        let drop_body = drop_impl
            .split("fn drop")
            .nth(1)
            .expect("SubOpGetCompletionGuard Drop impl must define fn drop");
        assert!(
            drop_body.contains(".completed(self.tx)"),
            "SubOpGetCompletionGuard::drop must call \
             op_manager.completed(self.tx) — see #4066"
        );
    }

    trait FindOrPanic {
        fn unwrap_or_default_pos(&self, needle: &str) -> usize;
    }
    impl FindOrPanic for str {
        fn unwrap_or_default_pos(&self, needle: &str) -> usize {
            self.find(needle).unwrap_or_else(|| {
                panic!("expected `{needle}` to appear in drive_relay_get_inner body")
            })
        }
    }
}