freenet 0.2.27

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
use freenet_stdlib::client_api::{ErrorKind, HostResponse};
use freenet_stdlib::prelude::*;
use std::collections::HashSet;
use std::fmt::Display;
use std::pin::Pin;
use std::{future::Future, time::Instant};

use crate::client_events::HostResult;
use crate::config::GlobalExecutor;
use crate::node::IsOperationCompleted;
use crate::{
    contract::{ContractHandlerEvent, StoreResponse},
    message::{InnerMessage, NetMessage, Transaction},
    node::{NetworkBridge, OpManager},
    operations::{OpInitialization, Operation},
    ring::{Location, PeerKeyLocation, RingError},
    tracing::{NetEventLog, OperationFailure, state_hash_full},
};
use either::Either;

use super::orphan_streams::{OrphanStreamError, STREAM_CLAIM_TIMEOUT};
use super::{OpEnum, OpError, OpOutcome, OperationResult, should_use_streaming};
use crate::transport::peer_connection::StreamId;

use self::messages::GetStreamingPayload;
pub(crate) use self::messages::{GetMsg, GetMsgResult};

/// Maximum number of retries to get values.
const MAX_RETRIES: usize = 10;

/// Maximum number of peer attempts at each hop level
const DEFAULT_MAX_BREADTH: usize = 3;

/// Minimum HTL for speculative retries.
///
/// Retries use a reduced HTL (capped at current_hop) to avoid full-depth
/// traversal storms. This floor ensures retries still reach peers 2-3 hops
/// away, which is the minimum useful search depth in any topology.
const MIN_RETRY_HTL: usize = 3;

pub(crate) fn start_op(
    instance_id: ContractInstanceId,
    fetch_contract: bool,
    subscribe: bool,
    blocking_subscribe: bool,
) -> GetOp {
    let contract_location = Location::from(&instance_id);
    let id = Transaction::new::<GetMsg>();
    tracing::debug!(tx = %id, "Requesting get contract {instance_id} @ loc({contract_location})");
    let state = Some(GetState::PrepareRequest(PrepareRequestData {
        instance_id,
        id,
        fetch_contract,
        subscribe,
        blocking_subscribe,
    }));
    GetOp {
        id,
        state,
        result: None,
        stats: Some(Box::new(GetStats {
            contract_location,
            next_peer: None,
            transfer_time: None,
            first_response_time: None,
        })),
        upstream_addr: None, // Local operation, no upstream peer
        local_fallback: None,
        auto_fetch: false,
        ack_received: false,
        speculative_paths: 0,
    }
}

/// Create a GET operation with a specific transaction ID (for operation deduplication)
pub(crate) fn start_op_with_id(
    instance_id: ContractInstanceId,
    fetch_contract: bool,
    subscribe: bool,
    blocking_subscribe: bool,
    id: Transaction,
) -> GetOp {
    let contract_location = Location::from(&instance_id);
    tracing::debug!(tx = %id, "Requesting get contract {instance_id} @ loc({contract_location}) with existing transaction ID");
    let state = Some(GetState::PrepareRequest(PrepareRequestData {
        instance_id,
        id,
        fetch_contract,
        subscribe,
        blocking_subscribe,
    }));
    GetOp {
        id,
        state,
        result: None,
        stats: Some(Box::new(GetStats {
            contract_location,
            next_peer: None,
            transfer_time: None,
            first_response_time: None,
        })),
        upstream_addr: None, // Local operation, no upstream peer
        local_fallback: None,
        auto_fetch: false,
        ack_received: false,
        speculative_paths: 0,
    }
}

/// Create a GET operation pre-targeted at a specific peer, bypassing normal routing.
/// Returns the operation and the message to send. Used for auto-fetching contracts
/// from peers known to have them (e.g., UPDATE senders).
pub(crate) fn start_targeted_op(
    instance_id: ContractInstanceId,
    target: PeerKeyLocation,
    max_hops_to_live: usize,
) -> (GetOp, GetMsg) {
    let contract_location = Location::from(&instance_id);
    let id = Transaction::new::<GetMsg>();
    tracing::debug!(
        tx = %id,
        "Requesting targeted get contract {instance_id} @ loc({contract_location})"
    );

    let visited = super::VisitedPeers::new(&id);
    let mut tried_peers = HashSet::new();
    if let Some(addr) = target.socket_addr() {
        tried_peers.insert(addr);
    }

    let state = Some(GetState::AwaitingResponse(AwaitingResponseData {
        instance_id,
        retries: 0,
        fetch_contract: true,
        requester: None,
        current_hop: max_hops_to_live,
        subscribe: false,
        blocking_subscribe: false,
        next_hop: target,
        tried_peers,
        alternatives: vec![],
        attempts_at_hop: 1,
        visited: visited.clone(),
    }));

    let msg = GetMsg::Request {
        id,
        instance_id,
        fetch_contract: true,
        htl: max_hops_to_live,
        visited,
    };

    let op = GetOp {
        id,
        state,
        result: None,
        stats: Some(Box::new(GetStats {
            contract_location,
            next_peer: None,
            transfer_time: None,
            first_response_time: None,
        })),
        upstream_addr: None,
        local_fallback: None,
        auto_fetch: true, // System-initiated, not a client request
        ack_received: false,
        speculative_paths: 0,
    };

    (op, msg)
}

/// Request to get the current value from a contract.
pub(crate) async fn request_get(
    op_manager: &OpManager,
    get_op: GetOp,
    visited: super::VisitedPeers,
) -> Result<(), OpError> {
    let (mut candidates, id, instance_id_val, _fetch_contract, local_fallback) = if let Some(
        GetState::PrepareRequest(data),
    ) =
        &get_op.state
    {
        let instance_id = &data.instance_id;
        let id = &data.id;
        let fetch_contract = &data.fetch_contract;
        // Check local storage to have a fallback, but prefer network for freshness.
        // This implements "network first, local fallback" to ensure we get the latest
        // version of contracts rather than serving potentially stale cached data.
        tracing::debug!(
            tx = %id,
            %instance_id,
            "GET: Checking local storage for fallback before network query"
        );

        let get_result = op_manager
            .notify_contract_handler(ContractHandlerEvent::GetQuery {
                instance_id: *instance_id,
                return_contract_code: *fetch_contract,
            })
            .await;

        let local_value = match get_result {
            Ok(ContractHandlerEvent::GetResponse {
                key: Some(key),
                response:
                    Ok(StoreResponse {
                        state: Some(state),
                        contract,
                    }),
            }) => {
                if *fetch_contract && contract.is_none() {
                    tracing::info!(
                        tx = %id,
                        %instance_id,
                        "GET: state available locally but contract code missing; will query peers"
                    );
                    None
                } else {
                    Some((key, state, contract))
                }
            }
            _ => None,
        };

        // Find peers to query - we prefer network over local cache for freshness
        let candidates = op_manager.ring.k_closest_potentially_hosting(
            instance_id,
            &visited,
            DEFAULT_MAX_BREADTH,
        );

        if candidates.is_empty() {
            // No peers available - use local cache if we have it
            if let Some((key, state, contract)) = local_value {
                tracing::info!(
                    tx = %id,
                    contract = %key,
                    phase = "complete",
                    "GET: No peers available, returning local cache"
                );

                let completed_op = GetOp {
                    id: *id,
                    state: Some(GetState::Finished(FinishedData { key })),
                    result: Some(GetResult {
                        key,
                        state,
                        contract,
                    }),
                    stats: get_op.stats,
                    upstream_addr: get_op.upstream_addr,
                    local_fallback: None,
                    auto_fetch: false,
                    ack_received: false,
                    speculative_paths: 0,
                };

                op_manager.push(*id, OpEnum::Get(completed_op)).await?;
                return Ok(());
            }

            // No peers AND no local cache - error
            tracing::warn!(
                tx = %id,
                contract = %instance_id,
                phase = "error",
                "GET: Contract not found locally and no peers available"
            );

            // Emit failure telemetry so this case is visible in production metrics
            if let Some(event) = NetEventLog::get_failure(
                id,
                &op_manager.ring,
                *instance_id,
                OperationFailure::NoPeersAvailable,
                None,
            ) {
                op_manager.ring.register_events(Either::Left(event)).await;
            }

            return Err(RingError::EmptyRing.into());
        }

        // Peers available - query network, keep local as fallback
        if local_value.is_some() {
            tracing::debug!(
                tx = %id,
                %instance_id,
                peer_count = candidates.len(),
                "GET: Have local cache, querying {} peer(s) for fresh version",
                candidates.len()
            );
        } else {
            tracing::debug!(
                tx = %id,
                %instance_id,
                peer_count = candidates.len(),
                "GET: No local cache, querying {} peer(s)",
                candidates.len()
            );
        }

        (candidates, *id, *instance_id, *fetch_contract, local_value)
    } else {
        return Err(OpError::UnexpectedOpState);
    };

    // Take the first candidate as the target
    let target = candidates.remove(0);
    tracing::debug!(
        tx = %id,
        target = %target,
        "Preparing get contract request",
    );

    match get_op.state {
        Some(GetState::PrepareRequest(data)) => {
            let (fetch_contract, subscribe, blocking_subscribe) =
                (data.fetch_contract, data.subscribe, data.blocking_subscribe);
            let mut tried_peers = HashSet::new();
            if let Some(addr) = target.socket_addr() {
                tried_peers.insert(addr);
            }

            let new_state = Some(GetState::AwaitingResponse(AwaitingResponseData {
                instance_id: instance_id_val,
                retries: 0,
                fetch_contract,
                requester: None,
                current_hop: op_manager.ring.max_hops_to_live,
                subscribe,
                blocking_subscribe,
                next_hop: target.clone(),
                tried_peers,
                alternatives: candidates,
                attempts_at_hop: 1,
                visited: visited.clone(),
            }));

            let msg = GetMsg::Request {
                id,
                instance_id: instance_id_val,
                fetch_contract,
                htl: op_manager.ring.max_hops_to_live,
                visited,
            };

            let op = GetOp {
                id,
                state: new_state,
                result: None,
                stats: get_op.stats.map(|mut s| {
                    s.next_peer = Some(target.clone());
                    s
                }),
                upstream_addr: get_op.upstream_addr,
                local_fallback, // Store local cache for fallback if network returns NotFound
                auto_fetch: get_op.auto_fetch,
                ack_received: false,
                speculative_paths: 0,
            };

            // Emit get_request telemetry when initiating a GET operation
            if let Some(event) = NetEventLog::get_request(
                &id,
                &op_manager.ring,
                instance_id_val,
                target,
                op_manager.ring.max_hops_to_live,
            ) {
                op_manager.ring.register_events(Either::Left(event)).await;
            }

            op_manager
                .notify_op_change(NetMessage::from(msg), OpEnum::Get(op))
                .await?;
        }
        _ => return Err(OpError::invalid_transition(get_op.id)),
    }
    Ok(())
}

// ── Type-state data structs ──────────────────────────────────────────────
//
// Each state in the GET state machine is a named struct with typed
// transition methods.  This gives compile-time guarantees:
//
//   ReceivedRequest ── (no transition methods, next state depends on message)
//   PrepareRequest ── into_awaiting_response() ──► AwaitingResponse
//   AwaitingResponse ── into_finished()         ──► Finished
//                    ── with_retry_peer()        ──► AwaitingResponse (retry at same hop)
//                    ── with_next_hop()           ──► AwaitingResponse (advance to next hop)
//
// Invalid transitions (e.g. Finished → PrepareRequest) are unrepresentable
// because the target type simply has no such method.

/// Data for the PrepareRequest state: originator preparing GET request.
#[derive(Debug)]
struct PrepareRequestData {
    instance_id: ContractInstanceId,
    id: Transaction,
    fetch_contract: bool,
    subscribe: bool,
    blocking_subscribe: bool,
}

impl PrepareRequestData {
    /// Transition to AwaitingResponse after sending the GET request.
    ///
    /// Encodes valid transition: PrepareRequest → AwaitingResponse.
    /// Carries forward instance_id, fetch_contract, subscribe, blocking_subscribe.
    #[allow(dead_code)] // Documents valid transition; see type-state pattern
    fn into_awaiting_response(
        self,
        requester: Option<PeerKeyLocation>,
        next_hop: PeerKeyLocation,
        alternatives: Vec<PeerKeyLocation>,
        visited: super::VisitedPeers,
    ) -> AwaitingResponseData {
        AwaitingResponseData {
            instance_id: self.instance_id,
            requester,
            fetch_contract: self.fetch_contract,
            retries: 0,
            current_hop: 0,
            subscribe: self.subscribe,
            blocking_subscribe: self.blocking_subscribe,
            next_hop,
            tried_peers: HashSet::new(),
            alternatives,
            attempts_at_hop: 0,
            visited,
        }
    }
}

/// Data for the AwaitingResponse state: request sent, waiting for downstream peer.
///
/// This is the most complex state, tracking retry logic across multiple hops.
#[derive(Debug)]
struct AwaitingResponseData {
    /// Contract being fetched (by instance_id since we may not have full key yet)
    instance_id: ContractInstanceId,
    /// If specified the peer waiting for the response upstream
    requester: Option<PeerKeyLocation>,
    fetch_contract: bool,
    retries: usize,
    current_hop: usize,
    subscribe: bool,
    blocking_subscribe: bool,
    /// Peer we are currently trying to reach.
    /// Note: With connection-based routing, this is only used for state tracking,
    /// not for response routing (which uses upstream_addr instead).
    #[allow(dead_code)]
    next_hop: PeerKeyLocation,
    /// Peers we've already tried at this hop level
    tried_peers: HashSet<std::net::SocketAddr>,
    /// Alternative peers we could still try at this hop
    alternatives: Vec<PeerKeyLocation>,
    /// How many peers we've tried at this hop
    attempts_at_hop: usize,
    /// Bloom filter tracking visited peers across all hops
    visited: super::VisitedPeers,
}

impl AwaitingResponseData {
    /// Transition to Finished on successful GET response.
    ///
    /// Encodes valid transition: AwaitingResponse → Finished.
    #[allow(dead_code)] // Documents valid transition; see type-state pattern
    fn into_finished(self, key: ContractKey) -> FinishedData {
        FinishedData { key }
    }
}

/// Data for the Finished state: GET operation completed successfully.
#[derive(Debug, Clone, Copy)]
struct FinishedData {
    key: ContractKey,
}

// ── State enum (wraps the typed structs) ─────────────────────────────────

#[derive(Debug)]
#[allow(clippy::large_enum_variant)]
enum GetState {
    /// A new petition for a get op received from another peer.
    /// Note: We use GetOp::upstream_addr for response routing (not PeerKeyLocation).
    ReceivedRequest,
    /// Preparing request for get op.
    PrepareRequest(PrepareRequestData),
    /// Awaiting response from petition.
    AwaitingResponse(AwaitingResponseData),
    /// Operation completed successfully
    Finished(FinishedData),
}

impl Display for GetState {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            GetState::ReceivedRequest => write!(f, "ReceivedRequest"),
            GetState::PrepareRequest(data) => {
                write!(
                    f,
                    "PrepareRequest(instance_id: {}, id: {}, fetch_contract: {}, subscribe: {})",
                    data.instance_id, data.id, data.fetch_contract, data.subscribe
                )
            }
            GetState::AwaitingResponse(data) => {
                write!(
                    f,
                    "AwaitingResponse(requester: {:?}, fetch_contract: {}, retries: {}, current_hop: {}, subscribe: {})",
                    data.requester,
                    data.fetch_contract,
                    data.retries,
                    data.current_hop,
                    data.subscribe
                )
            }
            GetState::Finished(data) => write!(f, "Finished(key: {})", data.key),
        }
    }
}

struct GetStats {
    /// Next peer in get path to be targeted
    next_peer: Option<PeerKeyLocation>,
    contract_location: Location,
    /// (start, end)
    first_response_time: Option<(Instant, Option<Instant>)>,
    /// (start, end)
    transfer_time: Option<(Instant, Option<Instant>)>,
}

#[derive(Clone)]
pub(crate) struct GetResult {
    key: ContractKey,
    pub state: WrappedState,
    pub contract: Option<ContractContainer>,
}

impl TryFrom<GetOp> for GetResult {
    type Error = OpError;

    fn try_from(value: GetOp) -> Result<Self, Self::Error> {
        match value.result {
            Some(r) => Ok(r),
            _ => Err(OpError::UnexpectedOpState),
        }
    }
}

pub(crate) struct GetOp {
    pub id: Transaction,
    state: Option<GetState>,
    pub(super) result: Option<GetResult>,
    stats: Option<Box<GetStats>>,
    /// The address we received this operation's message from.
    /// Used for connection-based routing: responses are sent back to this address.
    upstream_addr: Option<std::net::SocketAddr>,
    /// Local cached state to fall back to if network query fails or returns NotFound.
    /// This enables "network first, local fallback" behavior to ensure we get fresh data
    /// while still being able to serve cached content when the network is unavailable.
    local_fallback: Option<(ContractKey, WrappedState, Option<ContractContainer>)>,
    /// True when this GET was spawned internally by try_auto_fetch_contract,
    /// not by a client request. Used to avoid sending spurious timeout errors
    /// to a non-existent client.
    auto_fetch: bool,
    /// True when a downstream relay has acknowledged forwarding this request.
    /// Used by the GC task to distinguish "peer is dead" from "peer is working on it".
    pub(crate) ack_received: bool,
    /// Number of speculative parallel paths launched by the originator's GC task.
    /// Capped at MAX_SPECULATIVE_PATHS to bound network overhead.
    pub(crate) speculative_paths: u8,
}

impl GetOp {
    pub(super) fn outcome(&self) -> OpOutcome<'_> {
        if let Some((
            GetResult {
                state, contract, ..
            },
            GetStats {
                next_peer: Some(target_peer),
                contract_location,
                first_response_time: Some((response_start, Some(response_end))),
                transfer_time: Some((transfer_start, Some(transfer_end))),
                ..
            },
        )) = self.result.as_ref().zip(self.stats.as_deref())
        {
            let payload_size = state.size()
                + contract
                    .as_ref()
                    .map(|c| c.data().len())
                    .unwrap_or_default();
            OpOutcome::ContractOpSuccess {
                target_peer,
                contract_location: *contract_location,
                payload_size,
                first_response_time: *response_end - *response_start,
                payload_transfer_time: *transfer_end - *transfer_start,
            }
        } else if self.result.is_none() {
            // No result — if we have stats with a target peer, report as failure
            if let Some(GetStats {
                next_peer: Some(target_peer),
                contract_location,
                ..
            }) = self.stats.as_deref()
            {
                OpOutcome::ContractOpFailure {
                    target_peer,
                    contract_location: *contract_location,
                }
            } else {
                OpOutcome::Incomplete
            }
        } else if let Some(GetStats {
            next_peer: Some(target_peer),
            contract_location,
            ..
        }) = self.stats.as_deref()
        {
            // Result present but timing incomplete (e.g. streaming completed without
            // full handshake timing). Report as untimed success so the router still
            // gets feedback instead of silently dropping the outcome.
            OpOutcome::ContractOpSuccessUntimed {
                target_peer,
                contract_location: *contract_location,
            }
        } else {
            OpOutcome::Incomplete
        }
    }

    /// Extract the contract instance ID from the operation state.
    pub(crate) fn instance_id(&self) -> Option<ContractInstanceId> {
        match &self.state {
            Some(GetState::PrepareRequest(data)) => Some(data.instance_id),
            Some(GetState::AwaitingResponse(data)) => Some(data.instance_id),
            _ => None,
        }
    }

    /// Returns true if this GET was initiated by a local client (not forwarded from
    /// a peer and not a system-initiated auto-fetch).
    pub(crate) fn is_client_initiated(&self) -> bool {
        if self.auto_fetch {
            return false;
        }
        match &self.state {
            Some(GetState::PrepareRequest(_)) => true,
            Some(GetState::AwaitingResponse(data)) => data.requester.is_none(),
            Some(GetState::ReceivedRequest) | Some(GetState::Finished(_)) | None => false,
        }
    }

    /// Extract routing failure info for timeout reporting.
    /// Returns `(target_peer, contract_location)` if stats are available.
    pub(crate) fn failure_routing_info(&self) -> Option<(PeerKeyLocation, Location)> {
        self.stats.as_deref().and_then(|stats| {
            stats
                .next_peer
                .as_ref()
                .map(|peer| (peer.clone(), stats.contract_location))
        })
    }

    /// Handle aborted outbound connections by directly retrying with alternative peers.
    pub(crate) async fn handle_abort(mut self, op_manager: &OpManager) -> Result<(), OpError> {
        if let Some(GetState::AwaitingResponse(AwaitingResponseData {
            instance_id,
            requester,
            fetch_contract,
            retries,
            current_hop,
            subscribe,
            blocking_subscribe,
            next_hop: failed_peer,
            mut tried_peers,
            mut alternatives,
            attempts_at_hop,
            visited,
        })) = self.state.take()
        {
            // Mark the failed peer as tried
            if let Some(addr) = failed_peer.socket_addr() {
                tried_peers.insert(addr);
            }

            // Try the next alternative if available
            if !alternatives.is_empty() && attempts_at_hop < DEFAULT_MAX_BREADTH {
                let next_target = alternatives.remove(0);

                tracing::debug!(
                    tx = %self.id,
                    %instance_id,
                    next_target = %next_target,
                    "GET: Connection aborted, trying alternative peer"
                );

                if let Some(addr) = next_target.socket_addr() {
                    tried_peers.insert(addr);
                }

                let new_state = Some(GetState::AwaitingResponse(AwaitingResponseData {
                    instance_id,
                    requester,
                    fetch_contract,
                    retries,
                    current_hop,
                    subscribe,
                    blocking_subscribe,
                    next_hop: next_target,
                    tried_peers,
                    alternatives,
                    attempts_at_hop: attempts_at_hop + 1,
                    visited: visited.clone(),
                }));

                // Note: handle_abort uses current_hop directly (not the attempts-based
                // reduction from retry_with_next_alternative). Connection aborts are
                // immediate failures, not timeout-based retries, so they don't contribute
                // to retry storms the same way. The bloom filter and tried_peers already
                // prevent cycling through the same peers. (#3570)
                let msg = GetMsg::Request {
                    id: self.id,
                    instance_id,
                    fetch_contract,
                    htl: current_hop,
                    visited,
                };

                let op = GetOp {
                    id: self.id,
                    state: new_state,
                    result: None,
                    stats: self.stats,
                    upstream_addr: self.upstream_addr,
                    local_fallback: self.local_fallback,
                    auto_fetch: self.auto_fetch,
                    ack_received: false,
                    speculative_paths: 0,
                };

                op_manager
                    .notify_op_change(NetMessage::from(msg), OpEnum::Get(op))
                    .await?;
                return Err(OpError::StatePushed);
            }

            // No alternatives - look for new candidates
            if retries < MAX_RETRIES {
                let mut new_visited = visited.clone();
                for addr in &tried_peers {
                    new_visited.mark_visited(*addr);
                }

                let mut new_candidates = op_manager.ring.k_closest_potentially_hosting(
                    &instance_id,
                    &new_visited,
                    DEFAULT_MAX_BREADTH,
                );

                if !new_candidates.is_empty() {
                    let next_target = new_candidates.remove(0);

                    tracing::debug!(
                        tx = %self.id,
                        %instance_id,
                        next_target = %next_target,
                        "GET: Connection aborted, found new candidate"
                    );

                    let mut new_tried_peers = HashSet::new();
                    if let Some(addr) = next_target.socket_addr() {
                        new_tried_peers.insert(addr);
                    }

                    let new_state = Some(GetState::AwaitingResponse(AwaitingResponseData {
                        instance_id,
                        requester,
                        fetch_contract,
                        retries: retries + 1,
                        current_hop,
                        subscribe,
                        blocking_subscribe,
                        next_hop: next_target,
                        tried_peers: new_tried_peers,
                        alternatives: new_candidates,
                        attempts_at_hop: 1,
                        visited: new_visited.clone(),
                    }));

                    let msg = GetMsg::Request {
                        id: self.id,
                        instance_id,
                        fetch_contract,
                        htl: current_hop,
                        visited: new_visited,
                    };

                    let op = GetOp {
                        id: self.id,
                        state: new_state,
                        result: None,
                        stats: self.stats,
                        upstream_addr: self.upstream_addr,
                        local_fallback: self.local_fallback,
                        auto_fetch: self.auto_fetch,
                        ack_received: false,
                        speculative_paths: 0,
                    };

                    op_manager
                        .notify_op_change(NetMessage::from(msg), OpEnum::Get(op))
                        .await?;
                    return Err(OpError::StatePushed);
                }
            }

            // No alternatives and no new candidates - check for local fallback
            // If we have a local cache, use it instead of failing entirely
            if let Some((key, state, contract)) = self.local_fallback {
                tracing::info!(
                    tx = %self.id,
                    contract = %key,
                    phase = "complete",
                    "GET: Connection aborted, no peers available - returning local cache"
                );

                let completed_op = GetOp {
                    id: self.id,
                    state: Some(GetState::Finished(FinishedData { key })),
                    result: Some(GetResult {
                        key,
                        state,
                        contract,
                    }),
                    stats: self.stats,
                    upstream_addr: self.upstream_addr,
                    local_fallback: None,
                    auto_fetch: false,
                    ack_received: false,
                    speculative_paths: 0,
                };

                op_manager.push(self.id, OpEnum::Get(completed_op)).await?;
                return Ok(());
            }

            // No local fallback either - give up
            if let Some(upstream) = self.upstream_addr {
                // Send NotFound response back to upstream requester instead of letting them timeout
                tracing::warn!(
                    tx = %self.id,
                    %instance_id,
                    %upstream,
                    phase = "not_found",
                    "GET: Connection aborted, no peers available - sending NotFound to upstream"
                );
                // Emit telemetry: relay returning NotFound after abort
                let hop_count = Some(op_manager.ring.max_hops_to_live.saturating_sub(current_hop));
                if let Some(event) =
                    NetEventLog::get_not_found(&self.id, &op_manager.ring, instance_id, hop_count)
                {
                    op_manager.ring.register_events(Either::Left(event)).await;
                }

                let response_op = GetOp {
                    id: self.id,
                    state: None,
                    result: None,
                    stats: self.stats,
                    upstream_addr: self.upstream_addr,
                    local_fallback: None,
                    auto_fetch: false,
                    ack_received: false,
                    speculative_paths: 0,
                };

                op_manager
                    .notify_op_change(
                        NetMessage::from(GetMsg::Response {
                            id: self.id,
                            instance_id,
                            result: GetMsgResult::NotFound,
                        }),
                        OpEnum::Get(response_op),
                    )
                    .await?;
                return Err(OpError::StatePushed);
            } else {
                // Original requester - operation fails locally
                tracing::warn!(
                    tx = %self.id,
                    %instance_id,
                    phase = "not_found",
                    "GET: Connection aborted, no peers available - local operation fails"
                );

                // Emit failure event with hop_count
                let hop_count = Some(op_manager.ring.max_hops_to_live.saturating_sub(current_hop));
                if let Some(event) = NetEventLog::get_failure(
                    &self.id,
                    &op_manager.ring,
                    instance_id,
                    OperationFailure::NoPeersAvailable,
                    hop_count,
                ) {
                    op_manager.ring.register_events(Either::Left(event)).await;
                }

                let failed_op = GetOp {
                    id: self.id,
                    state: None,
                    result: None,
                    stats: self.stats,
                    upstream_addr: self.upstream_addr,
                    local_fallback: None,
                    auto_fetch: false,
                    ack_received: false,
                    speculative_paths: 0,
                };
                op_manager.push(self.id, OpEnum::Get(failed_op)).await?;
                return Ok(());
            }
        }

        // If we weren't awaiting a response, just put the op back.
        // No retry needed; another handler may pick it up later.
        op_manager.push(self.id, OpEnum::Get(self)).await?;
        Ok(())
    }

    pub(super) fn finalized(&self) -> bool {
        self.result.is_some() && matches!(self.state, Some(GetState::Finished(_)))
    }

    pub(super) fn to_host_result(&self) -> HostResult {
        match &self.result {
            Some(GetResult {
                key,
                state,
                contract,
            }) => Ok(HostResponse::ContractResponse(
                freenet_stdlib::client_api::ContractResponse::GetResponse {
                    key: *key,
                    contract: contract.clone(),
                    state: state.clone(),
                },
            )),
            None => Err(ErrorKind::OperationError {
                cause: "get didn't finish successfully".into(),
            }
            .into()),
        }
    }

    /// Get the next hop address if this operation is in a state that needs to send
    /// an outbound message. Used for hop-by-hop routing.
    pub(crate) fn get_next_hop_addr(&self) -> Option<std::net::SocketAddr> {
        match &self.state {
            Some(GetState::AwaitingResponse(data)) => data.next_hop.socket_addr(),
            _ => None,
        }
    }

    /// Get the current hop count (remaining HTL) for this operation.
    /// Returns None if the operation is not in AwaitingResponse state.
    pub(crate) fn get_current_hop(&self) -> Option<usize> {
        match &self.state {
            Some(GetState::AwaitingResponse(data)) => Some(data.current_hop),
            _ => None,
        }
    }

    /// Try to retry this GET operation by sending to the next alternative peer.
    /// If local alternatives are exhausted, `fallback_peers` provides additional
    /// candidates (e.g., all connected peers for DBF search).
    /// Returns `Ok((new_op, msg))` if a peer was available,
    /// `Err(self)` if no peers remain (caller gets ownership back).
    pub(crate) fn retry_with_next_alternative(
        mut self,
        max_hops_to_live: usize,
        fallback_peers: &[PeerKeyLocation],
    ) -> Result<(GetOp, GetMsg), Box<GetOp>> {
        let state = match self.state.take() {
            Some(s) => s,
            None => return Err(Box::new(self)),
        };
        match state {
            GetState::AwaitingResponse(mut data) => {
                // If local alternatives exhausted, inject fallback peers we haven't tried.
                // Filter through BOTH tried_peers (this hop) AND visited bloom filter
                // (all hops) to avoid retry storms cycling through the same peers (#3570).
                if data.alternatives.is_empty() && !fallback_peers.is_empty() {
                    for peer in fallback_peers {
                        if let Some(addr) = peer.socket_addr() {
                            if !data.tried_peers.contains(&addr)
                                && !data.visited.probably_visited(addr)
                            {
                                data.alternatives.push(peer.clone());
                            }
                        }
                    }
                    if !data.alternatives.is_empty() {
                        tracing::info!(
                            tx = %self.id,
                            contract = %data.instance_id,
                            new_candidates = data.alternatives.len(),
                            "GET broadening search to all connected peers (DBF fallback)"
                        );
                    }
                }

                if data.alternatives.is_empty() {
                    self.state = Some(GetState::AwaitingResponse(data));
                    return Err(Box::new(self));
                }

                let next_target = data.alternatives.remove(0);
                let instance_id = data.instance_id;
                let fetch_contract = data.fetch_contract;
                if let Some(addr) = next_target.socket_addr() {
                    data.tried_peers.insert(addr);
                    // Mark in bloom filter so downstream peers won't forward back,
                    // and future retries won't select this peer again (#3570).
                    data.visited.mark_visited(addr);
                }
                tracing::info!(
                    tx = %self.id,
                    contract = %instance_id,
                    target = %next_target,
                    remaining_alternatives = data.alternatives.len(),
                    "GET retrying with alternative peer after timeout"
                );
                // Update stats to point to the new target so timeouts/failures
                // are reported against the correct peer (#3527).
                if let Some(ref mut s) = self.stats {
                    s.next_peer = Some(next_target.clone());
                }
                data.next_hop = next_target;
                data.attempts_at_hop += 1;
                let visited = data.visited.clone();

                // Reduce HTL on each retry to avoid full-depth traversal storms (#3570).
                // Halve the HTL for each retry attempt, floored at MIN_RETRY_HTL.
                // This limits the blast radius of retries while still allowing the
                // request to reach nearby contract holders.
                let retry_htl = (max_hops_to_live / (data.attempts_at_hop.max(1)))
                    .max(MIN_RETRY_HTL)
                    .min(max_hops_to_live);

                self.state = Some(GetState::AwaitingResponse(data));

                let msg = GetMsg::Request {
                    id: self.id,
                    instance_id,
                    fetch_contract,
                    htl: retry_htl,
                    visited,
                };

                Ok((self, msg))
            }
            other @ GetState::ReceivedRequest
            | other @ GetState::PrepareRequest(_)
            | other @ GetState::Finished(_) => {
                self.state = Some(other);
                Err(Box::new(self))
            }
        }
    }
}

impl Operation for GetOp {
    type Message = GetMsg;
    type Result = GetResult;

    async fn load_or_init<'a>(
        op_manager: &'a OpManager,
        msg: &'a Self::Message,
        source_addr: Option<std::net::SocketAddr>,
    ) -> Result<OpInitialization<Self>, OpError> {
        let tx = *msg.id();
        match op_manager.pop(msg.id()) {
            Ok(Some(OpEnum::Get(get_op))) => {
                Ok(OpInitialization {
                    op: get_op,
                    source_addr,
                })
                // was an existing operation, other peer messaged back
            }
            Ok(Some(op)) => {
                if let Err(e) = op_manager.push(tx, op).await {
                    tracing::warn!(tx = %tx, error = %e, "failed to push mismatched op back");
                }
                Err(OpError::OpNotPresent(tx))
            }
            Ok(None) => {
                // Check if this is a response message - if so, the operation was likely
                // cleaned up due to timeout and we should not create a new operation
                if matches!(
                    msg,
                    GetMsg::Response { .. }
                        | GetMsg::ResponseStreaming { .. }
                        | GetMsg::ForwardingAck { .. }
                ) {
                    tracing::debug!(
                        tx = %tx,
                        phase = "load_or_init",
                        "GET response/ack arrived for non-existent operation (likely timed out)"
                    );
                    return Err(OpError::OpNotPresent(tx));
                }

                // new request to get a value for a contract, initialize the machine
                Ok(OpInitialization {
                    op: Self {
                        state: Some(GetState::ReceivedRequest),
                        id: tx,
                        result: None,
                        stats: None, // don't care about stats in target peers
                        upstream_addr: source_addr, // Connection-based routing: store who sent us this request
                        local_fallback: None,       // Remote requests don't have local fallback
                        auto_fetch: false,
                        ack_received: false,
                        speculative_paths: 0,
                    },
                    source_addr,
                })
            }
            Err(err) => Err(err.into()),
        }
    }

    fn id(&self) -> &Transaction {
        &self.id
    }

    fn process_message<'a, NB: NetworkBridge>(
        self,
        conn_manager: &'a mut NB,
        op_manager: &'a OpManager,
        input: &'a Self::Message,
        source_addr: Option<std::net::SocketAddr>,
    ) -> Pin<Box<dyn Future<Output = Result<OperationResult, OpError>> + Send + 'a>> {
        Box::pin(async move {
            // Take fields early since self will be partially moved
            let mut local_fallback = self.local_fallback;
            let auto_fetch = self.auto_fetch;
            #[allow(unused_assignments)]
            let mut return_msg = None;
            #[allow(unused_assignments)]
            let mut new_state = None;
            let mut result = None;
            let mut stats = self.stats;
            let mut stream_data: Option<(StreamId, bytes::Bytes)> = None;

            // Look up sender's PeerKeyLocation from source address for logging/routing
            // This replaces the sender field that was previously embedded in messages
            let sender_from_addr = source_addr.and_then(|addr| {
                op_manager
                    .ring
                    .connection_manager
                    .get_peer_location_by_addr(addr)
            });

            match input {
                GetMsg::Request {
                    instance_id,
                    id,
                    fetch_contract,
                    htl,
                    visited,
                } => {
                    // Handle GET request - either initial or forwarded
                    let ring_max_htl = op_manager.ring.max_hops_to_live.max(1);
                    let htl = (*htl).min(ring_max_htl);
                    let id = *id;
                    let instance_id = *instance_id;
                    let fetch_contract = *fetch_contract;

                    // Use sender_from_addr for logging (falls back to source_addr if lookup fails)
                    let sender_display = sender_from_addr
                        .as_ref()
                        .map(|s| s.to_string())
                        .unwrap_or_else(|| {
                            source_addr
                                .map(|a| a.to_string())
                                .unwrap_or_else(|| "unknown".to_string())
                        });
                    tracing::info!(
                        tx = %id,
                        %instance_id,
                        peer_addr = %sender_display,
                        fetch_contract,
                        htl,
                        skip = ?visited,
                        phase = "request",
                        "GET Request received"
                    );

                    // Use sender_from_addr if available, but allow processing without it.
                    // The sender may not be in our ring if this is a transient connection
                    // or in simulation where direct sends bypass connection establishment.
                    // Routing uses upstream_addr (stored from source_addr), not sender.
                    let sender = sender_from_addr.clone();

                    // Check if operation is already completed
                    if matches!(self.state, Some(GetState::Finished(_))) {
                        tracing::debug!(
                            tx = %id,
                            "GET: Request received for already completed operation, ignoring duplicate request"
                        );
                        // Return the operation in its current state
                        new_state = self.state;
                        return_msg = None;
                        result = self.result;
                    } else if htl == 0 {
                        // HTL exhausted - send NotFound response
                        tracing::warn!(
                            tx = %id,
                            %instance_id,
                            peer_addr = %sender_display,
                            htl = 0,
                            phase = "not_found",
                            "GET Request exhausted HTL - sending NotFound response"
                        );
                        // Emit telemetry: relay returning NotFound due to HTL exhaustion
                        if let Some(event) = NetEventLog::get_not_found(
                            &id,
                            &op_manager.ring,
                            instance_id,
                            Some(op_manager.ring.max_hops_to_live.saturating_sub(htl)),
                        ) {
                            op_manager.ring.register_events(Either::Left(event)).await;
                        }
                        return build_op_result(GetOpResult {
                            id,
                            state: None,
                            msg: Some(GetMsg::Response {
                                id,
                                instance_id,
                                result: GetMsgResult::NotFound,
                            }),
                            result: None,
                            stats,
                            upstream_addr: self.upstream_addr,
                            stream_data: None,
                            local_fallback: None,
                            auto_fetch: false,
                        });
                    } else {
                        // Normal case: operation should be in ReceivedRequest or AwaitingResponse state
                        debug_assert!(matches!(
                            self.state,
                            Some(GetState::ReceivedRequest) | Some(GetState::AwaitingResponse(_))
                        ));
                        tracing::debug!(
                            tx = %id,
                            %instance_id,
                            htl,
                            "GET: Request processing in state {:?}",
                            self.state
                        );

                        // Initialize/update stats for tracking the operation
                        let this_peer = op_manager.ring.connection_manager.own_location();
                        if stats.is_none() {
                            stats = Some(Box::new(GetStats {
                                contract_location: Location::from(&instance_id),
                                next_peer: Some(this_peer.clone()),
                                transfer_time: None,
                                first_response_time: None,
                            }));
                        } else if let Some(s) = stats.as_mut() {
                            s.next_peer = Some(this_peer.clone());
                        }

                        // Update skip list with current peer address and sender address
                        // Restore hash keys after deserialization (they're derived from tx)
                        let mut new_visited = visited.clone().with_transaction(&id);
                        if let Some(addr) = this_peer.socket_addr() {
                            new_visited.mark_visited(addr);
                        }
                        // Also mark the sender to prevent routing back to them
                        // This is critical for preventing request cycles, especially when
                        // a node has limited connections (e.g., only connected to gateway)
                        if let Some(addr) = source_addr {
                            new_visited.mark_visited(addr);
                        }

                        // First check if we have the contract locally before forwarding
                        let get_result = op_manager
                            .notify_contract_handler(ContractHandlerEvent::GetQuery {
                                instance_id,
                                return_contract_code: fetch_contract,
                            })
                            .await;

                        // GetResponse now returns key: Option<ContractKey>
                        let local_value = match get_result {
                            Ok(ContractHandlerEvent::GetResponse {
                                key: Some(key),
                                response:
                                    Ok(StoreResponse {
                                        state: Some(state),
                                        contract,
                                    }),
                            }) => {
                                if fetch_contract && contract.is_none() {
                                    tracing::info!(
                                        tx = %id,
                                        %instance_id,
                                        %this_peer,
                                        fetch_contract,
                                        "GET: state available locally but contract code missing; forwarding GET"
                                    );
                                    None
                                } else {
                                    Some((key, state, contract))
                                }
                            }
                            _ => None,
                        };

                        // Relay peers in ReceivedRequest: prefer fresh network state,
                        // local cache is fallback only. Store local value and forward.
                        let local_value = if self.upstream_addr.is_some()
                            && matches!(self.state, Some(GetState::ReceivedRequest))
                        {
                            if let Some(lv) = local_value {
                                tracing::debug!(
                                    tx = %id,
                                    "Relay peer deferring local cache, forwarding GET for fresh state"
                                );
                                local_fallback = Some(lv);
                            }
                            None
                        } else {
                            local_value
                        };

                        if let Some((key, state, contract)) = local_value {
                            // Contract found locally!
                            tracing::info!(
                                tx = %id,
                                contract = %key,
                                fetch_contract,
                                phase = "complete",
                                "GET: contract found locally"
                            );

                            // Register the GET requester's interest in this contract so that
                            // update broadcasts include them as a target. This is critical for
                            // partitioned topologies: the requester's auto-subscribe may route
                            // to a blocked peer instead of back to us, so we register interest
                            // proactively when serving the GET response.
                            if let Some(upstream_addr) = self.upstream_addr {
                                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.clone());
                                    op_manager
                                        .interest_manager
                                        .register_peer_interest(&key, peer_key, None, false);
                                    tracing::debug!(
                                        tx = %id,
                                        contract = %key,
                                        requester = %upstream_addr,
                                        "Registered GET requester interest for update broadcasts"
                                    );
                                }
                            }

                            // Note: ResponseSent telemetry is emitted by from_outbound_msg()
                            // when the message is actually sent, avoiding duplicate events.

                            // Check if this is a forwarded request or a local request
                            // Use upstream_addr (the actual socket address) not requester (PeerKeyLocation lookup)
                            // because get_peer_location_by_addr() can fail for transient connections
                            match &self.state {
                                Some(GetState::ReceivedRequest) if self.upstream_addr.is_some() => {
                                    // This is a forwarded request - send result back to upstream
                                    tracing::debug!(tx = %id, "Returning contract {} to upstream", key);
                                    new_state = None;
                                    let store_response = StoreResponse {
                                        state: Some(state),
                                        contract,
                                    };
                                    let includes_contract = store_response.contract.is_some();
                                    let payload = GetStreamingPayload {
                                        key,
                                        value: store_response,
                                    };
                                    let payload_bytes =
                                        bincode::serialize(&payload).map_err(|e| {
                                            OpError::NotificationChannelError(format!(
                                                "Failed to serialize streaming payload: {e}"
                                            ))
                                        })?;
                                    let payload_size = payload_bytes.len();
                                    if should_use_streaming(
                                        op_manager.streaming_threshold,
                                        payload_size,
                                    ) {
                                        let sid = StreamId::next_operations();
                                        tracing::info!(
                                            tx = %id,
                                            stream_id = %sid,
                                            payload_size,
                                            "GET response using operations-level streaming"
                                        );
                                        return_msg = Some(GetMsg::ResponseStreaming {
                                            id,
                                            instance_id: *payload.key.id(),
                                            stream_id: sid,
                                            key: payload.key,
                                            total_size: payload_size as u64,
                                            includes_contract,
                                        });
                                        stream_data =
                                            Some((sid, bytes::Bytes::from(payload_bytes)));
                                    } else {
                                        return_msg = Some(GetMsg::Response {
                                            id,
                                            instance_id: *payload.key.id(),
                                            result: GetMsgResult::Found {
                                                key: payload.key,
                                                value: payload.value,
                                            },
                                        });
                                    }
                                }
                                Some(GetState::AwaitingResponse(_))
                                    if self.upstream_addr.is_some() =>
                                {
                                    // Forward contract to upstream
                                    new_state = None;
                                    tracing::debug!(tx = %id, "Returning contract {} to upstream", key);
                                    let store_response = StoreResponse {
                                        state: Some(state),
                                        contract,
                                    };
                                    let includes_contract = store_response.contract.is_some();
                                    let payload = GetStreamingPayload {
                                        key,
                                        value: store_response,
                                    };
                                    let payload_bytes =
                                        bincode::serialize(&payload).map_err(|e| {
                                            OpError::NotificationChannelError(format!(
                                                "Failed to serialize streaming payload: {e}"
                                            ))
                                        })?;
                                    let payload_size = payload_bytes.len();
                                    if should_use_streaming(
                                        op_manager.streaming_threshold,
                                        payload_size,
                                    ) {
                                        let sid = StreamId::next_operations();
                                        tracing::info!(
                                            tx = %id,
                                            stream_id = %sid,
                                            payload_size,
                                            "GET response using operations-level streaming"
                                        );
                                        return_msg = Some(GetMsg::ResponseStreaming {
                                            id,
                                            instance_id: *payload.key.id(),
                                            stream_id: sid,
                                            key: payload.key,
                                            total_size: payload_size as u64,
                                            includes_contract,
                                        });
                                        stream_data =
                                            Some((sid, bytes::Bytes::from(payload_bytes)));
                                    } else {
                                        return_msg = Some(GetMsg::Response {
                                            id,
                                            instance_id: *payload.key.id(),
                                            result: GetMsgResult::Found {
                                                key: payload.key,
                                                value: payload.value,
                                            },
                                        });
                                    }
                                }
                                Some(GetState::AwaitingResponse(AwaitingResponseData {
                                    requester: None,
                                    ..
                                })) => {
                                    // Operation completed for original requester
                                    tracing::debug!(
                                        tx = %id,
                                        "Completed operation, get response received for contract {key}"
                                    );
                                    new_state = Some(GetState::Finished(FinishedData { key }));
                                    return_msg = None;
                                    result = Some(GetResult {
                                        key,
                                        state,
                                        contract,
                                    });
                                }
                                _ => {
                                    // This is the original requester (locally initiated request)
                                    new_state = Some(GetState::Finished(FinishedData { key }));
                                    return_msg = None;
                                    result = Some(GetResult {
                                        key,
                                        state,
                                        contract,
                                    });
                                }
                            }
                        } else {
                            // Contract not found locally (or missing code), proceed with forwarding
                            tracing::debug!(
                                tx = %id,
                                %instance_id,
                                %this_peer,
                                sender = ?sender,
                                "Contract not found @ peer, forwarding to other peers"
                            );

                            // Send ForwardingAck to upstream peer before forwarding.
                            // This tells the upstream "I'm working on it" so the GC task
                            // can distinguish dead peers from slow multi-hop chains.
                            if let Some(upstream) = self.upstream_addr {
                                let ack =
                                    NetMessage::from(GetMsg::ForwardingAck { id, instance_id });
                                drop(conn_manager.send(upstream, ack).await);

                                // Emit telemetry for ForwardingAck sent (#3570 diagnostics)
                                let upstream_peer = op_manager
                                    .ring
                                    .connection_manager
                                    .get_peer_by_addr(upstream)
                                    .unwrap_or_else(|| {
                                        op_manager.ring.connection_manager.own_location()
                                    });
                                if let Some(event) = NetEventLog::get_forwarding_ack_sent(
                                    &id,
                                    &op_manager.ring,
                                    instance_id,
                                    upstream_peer,
                                ) {
                                    op_manager.ring.register_events(Either::Left(event)).await;
                                }
                            }

                            // Forward using standard routing helper
                            // Note: target is determined by routing, sender from source_addr
                            return try_forward_or_return(
                                id,
                                instance_id,
                                (htl, fetch_contract),
                                (this_peer, sender),
                                new_visited,
                                op_manager,
                                stats,
                                self.upstream_addr,
                                local_fallback,
                            )
                            .await;
                        }
                    }
                }
                GetMsg::Response {
                    id,
                    instance_id,
                    result: GetMsgResult::NotFound,
                } => {
                    let id = *id;
                    let instance_id = *instance_id;

                    // Use sender_from_addr for logging (optional - sender may not be in ring)
                    let sender = sender_from_addr.clone();

                    tracing::info!(
                        tx = %id,
                        %instance_id,
                        sender = ?sender,
                        phase = "not_found",
                        "GET NotFound response received"
                    );
                    // Handle case where contract was not found
                    let this_peer = op_manager.ring.connection_manager.own_location();
                    tracing::warn!(
                        tx = %id,
                        %instance_id,
                        peer_addr = %this_peer,
                        sender = ?sender,
                        phase = "retry",
                        "Contract not found at peer, retrying with other peers"
                    );

                    match self.state {
                        Some(GetState::AwaitingResponse(AwaitingResponseData {
                            fetch_contract,
                            retries,
                            requester,
                            current_hop,
                            subscribe,
                            blocking_subscribe,
                            mut tried_peers,
                            mut alternatives,
                            attempts_at_hop,
                            next_hop: _,
                            visited,
                            instance_id: state_instance_id,
                            ..
                        })) => {
                            // Use instance_id from state for consistency
                            let instance_id = state_instance_id;

                            // Add the failed peer to tried list
                            if let Some(addr) = sender.as_ref().and_then(|s| s.socket_addr()) {
                                tried_peers.insert(addr);
                            }

                            // First, check if we have alternatives at this hop level
                            if !alternatives.is_empty() && attempts_at_hop < DEFAULT_MAX_BREADTH {
                                // Try the next alternative
                                let next_target = alternatives.remove(0);

                                tracing::info!(
                                    tx = %id,
                                    %instance_id,
                                    peer_addr = %next_target,
                                    fetch_contract,
                                    attempts_at_hop = attempts_at_hop + 1,
                                    max_attempts = DEFAULT_MAX_BREADTH,
                                    tried = ?tried_peers,
                                    remaining_alternatives = ?alternatives,
                                    phase = "retry",
                                    "Trying alternative peer at same hop level"
                                );

                                return_msg = Some(GetMsg::Request {
                                    id,
                                    instance_id,
                                    fetch_contract,
                                    htl: current_hop,
                                    visited: visited.clone(),
                                });

                                // Update state with the new alternative being tried
                                if let Some(addr) = next_target.socket_addr() {
                                    tried_peers.insert(addr);
                                }
                                let updated_tried_peers = tried_peers.clone();
                                new_state =
                                    Some(GetState::AwaitingResponse(AwaitingResponseData {
                                        retries,
                                        fetch_contract,
                                        requester: requester.clone(),
                                        current_hop,
                                        subscribe,
                                        blocking_subscribe,
                                        tried_peers: updated_tried_peers.clone(),
                                        alternatives,
                                        attempts_at_hop: attempts_at_hop + 1,
                                        instance_id,
                                        next_hop: next_target,
                                        // Preserve the accumulated visited so future candidate
                                        // selection still avoids already-specified peers; tried_peers
                                        // tracks attempts at this hop.
                                        visited: visited.clone(),
                                    }));
                            } else if retries < MAX_RETRIES {
                                // No more alternatives at this hop, try finding new peers
                                let mut new_visited = visited.clone();
                                for addr in &tried_peers {
                                    new_visited.mark_visited(*addr);
                                }

                                // Get new candidates excluding all tried peers
                                let mut new_candidates =
                                    op_manager.ring.k_closest_potentially_hosting(
                                        &instance_id,
                                        &new_visited,
                                        DEFAULT_MAX_BREADTH,
                                    );

                                tracing::info!(
                                    tx = %id,
                                    %instance_id,
                                    new_candidates = ?new_candidates,
                                    skip = ?new_visited,
                                    htl = current_hop,
                                    retries = retries + 1,
                                    phase = "retry",
                                    "GET seeking new candidates after exhausted alternatives"
                                );

                                if !new_candidates.is_empty() {
                                    // Try with the best new peer
                                    let target = new_candidates.remove(0);
                                    return_msg = Some(GetMsg::Request {
                                        id,
                                        instance_id,
                                        fetch_contract,
                                        htl: current_hop,
                                        visited: new_visited.clone(),
                                    });

                                    // Reset for new round of attempts
                                    let mut new_tried_peers = HashSet::new();
                                    if let Some(addr) = target.socket_addr() {
                                        new_tried_peers.insert(addr);
                                    }

                                    new_state =
                                        Some(GetState::AwaitingResponse(AwaitingResponseData {
                                            retries: retries + 1,
                                            fetch_contract,
                                            requester: requester.clone(),
                                            current_hop,
                                            subscribe,
                                            blocking_subscribe,
                                            tried_peers: new_tried_peers,
                                            alternatives: new_candidates,
                                            attempts_at_hop: 1,
                                            instance_id,
                                            next_hop: target,
                                            visited: new_visited.clone(),
                                        }));
                                } else if let Some(requester_peer) = requester.clone() {
                                    // No more peers to try — serve local fallback if available
                                    if let Some((key, state, contract)) = local_fallback.take() {
                                        tracing::info!(
                                            tx = %id,
                                            contract = %key,
                                            "Relay serving local cache as fallback (network returned NotFound)"
                                        );
                                        return_msg = Some(build_fallback_found_response(
                                            id,
                                            instance_id,
                                            key,
                                            state,
                                            contract,
                                        ));
                                    } else {
                                        tracing::warn!(
                                            tx = %id,
                                            %instance_id,
                                            peer_addr = %this_peer,
                                            target = %requester_peer,
                                            tried = ?tried_peers,
                                            skip = ?new_visited,
                                            phase = "not_found",
                                            "No other peers found while trying to get the contract, returning NotFound to requester"
                                        );
                                        return_msg = Some(GetMsg::Response {
                                            id,
                                            instance_id,
                                            result: GetMsgResult::NotFound,
                                        });
                                    }
                                } else {
                                    // Original requester - check for local fallback before failing
                                    if let Some((key, state, contract)) = local_fallback.take() {
                                        tracing::info!(
                                            tx = %id,
                                            contract = %key,
                                            phase = "complete",
                                            "GET: Network returned NotFound, returning local cache and re-hosting to network"
                                        );

                                        // Complete with local cached version
                                        new_state = Some(GetState::Finished(FinishedData { key }));
                                        return_msg = None;
                                        result = Some(GetResult {
                                            key,
                                            state: state.clone(),
                                            contract: contract.clone(),
                                        });

                                        // Re-host to the network with our local copy
                                        if let Some(contract_code) = contract {
                                            tracing::info!(
                                                tx = %id,
                                                %key,
                                                "Re-publishing to network after NotFound response"
                                            );
                                            let put_result = op_manager
                                                .notify_contract_handler(
                                                    ContractHandlerEvent::PutQuery {
                                                        key,
                                                        state,
                                                        related_contracts:
                                                            RelatedContracts::default(),
                                                        contract: Some(contract_code),
                                                    },
                                                )
                                                .await;
                                            match put_result {
                                                Ok(ContractHandlerEvent::PutResponse {
                                                    new_value: Ok(_),
                                                    ..
                                                }) => {
                                                    tracing::debug!(tx = %id, %key, "Re-hosted contract to network");
                                                    super::announce_contract_hosted(
                                                        op_manager, &key,
                                                    )
                                                    .await;
                                                }
                                                _ => {
                                                    tracing::warn!(tx = %id, %key, "Failed to re-host contract");
                                                }
                                            }
                                        }
                                    } else {
                                        // No local fallback - operation failed
                                        tracing::error!(
                                            tx = %id,
                                            %instance_id,
                                            tried = ?tried_peers,
                                            skip = ?visited,
                                            phase = "not_found",
                                            "Failed getting contract, not found after max retries"
                                        );

                                        // Emit get_not_found telemetry
                                        let hop_count = Some(
                                            op_manager
                                                .ring
                                                .max_hops_to_live
                                                .saturating_sub(current_hop),
                                        );
                                        if let Some(event) = NetEventLog::get_not_found(
                                            &id,
                                            &op_manager.ring,
                                            instance_id,
                                            hop_count,
                                        ) {
                                            op_manager
                                                .ring
                                                .register_events(Either::Left(event))
                                                .await;
                                        }

                                        notify_get_failed(
                                            op_manager,
                                            id,
                                            &format!(
                                                "contract {instance_id} not found after exhausting all peers"
                                            ),
                                        );
                                        return_msg = None;
                                        new_state = None;
                                    }
                                }
                            } else {
                                // Max retries reached
                                tracing::error!(
                                    tx = %id,
                                    %instance_id,
                                    phase = "not_found",
                                    "Failed getting contract, reached max retries"
                                );

                                if let Some(requester_peer) = requester.clone() {
                                    // No more peers to try — serve local fallback if available
                                    if let Some((key, state, contract)) = local_fallback.take() {
                                        tracing::info!(
                                            tx = %id,
                                            contract = %key,
                                            "Relay serving local cache as fallback (max retries, network returned NotFound)"
                                        );
                                        return_msg = Some(build_fallback_found_response(
                                            id,
                                            instance_id,
                                            key,
                                            state,
                                            contract,
                                        ));
                                    } else {
                                        tracing::warn!(
                                            tx = %id,
                                            %instance_id,
                                            peer_addr = %this_peer,
                                            target = %requester_peer,
                                            tried = ?tried_peers,
                                            skip = ?visited,
                                            phase = "not_found",
                                            "No other peers found, returning NotFound to requester"
                                        );
                                        return_msg = Some(GetMsg::Response {
                                            id,
                                            instance_id,
                                            result: GetMsgResult::NotFound,
                                        });
                                    }
                                    new_state = None;
                                } else {
                                    // Original requester - check for local fallback before failing
                                    if let Some((key, state, contract)) = local_fallback.take() {
                                        tracing::info!(
                                            tx = %id,
                                            contract = %key,
                                            phase = "complete",
                                            "GET: Max retries reached, returning local cache and re-hosting to network"
                                        );

                                        // Complete with local cached version
                                        new_state = Some(GetState::Finished(FinishedData { key }));
                                        return_msg = None;
                                        result = Some(GetResult {
                                            key,
                                            state: state.clone(),
                                            contract: contract.clone(),
                                        });

                                        // Re-host to the network with our local copy
                                        if let Some(contract_code) = contract {
                                            tracing::info!(
                                                tx = %id,
                                                %key,
                                                "Re-publishing to network after NotFound (max retries)"
                                            );
                                            let put_result = op_manager
                                                .notify_contract_handler(
                                                    ContractHandlerEvent::PutQuery {
                                                        key,
                                                        state,
                                                        related_contracts:
                                                            RelatedContracts::default(),
                                                        contract: Some(contract_code),
                                                    },
                                                )
                                                .await;
                                            match put_result {
                                                Ok(ContractHandlerEvent::PutResponse {
                                                    new_value: Ok(_),
                                                    ..
                                                }) => {
                                                    tracing::debug!(tx = %id, %key, "Re-hosted contract to network");
                                                    super::announce_contract_hosted(
                                                        op_manager, &key,
                                                    )
                                                    .await;
                                                }
                                                _ => {
                                                    tracing::warn!(tx = %id, %key, "Failed to re-host contract");
                                                }
                                            }
                                        }
                                    } else {
                                        // No local fallback - operation failed
                                        tracing::error!(
                                            tx = %id,
                                            %instance_id,
                                            phase = "not_found",
                                            "Failed getting contract, reached max retries"
                                        );

                                        // Emit get_not_found telemetry
                                        let hop_count = Some(
                                            op_manager
                                                .ring
                                                .max_hops_to_live
                                                .saturating_sub(current_hop),
                                        );
                                        if let Some(event) = NetEventLog::get_not_found(
                                            &id,
                                            &op_manager.ring,
                                            instance_id,
                                            hop_count,
                                        ) {
                                            op_manager
                                                .ring
                                                .register_events(Either::Left(event))
                                                .await;
                                        }

                                        notify_get_failed(
                                            op_manager,
                                            id,
                                            &format!(
                                                "contract {instance_id} not found after max retries"
                                            ),
                                        );
                                        return_msg = None;
                                        new_state = None;
                                    }
                                }
                            }
                        }
                        Some(GetState::ReceivedRequest) => {
                            // Return NotFound to sender
                            tracing::debug!(tx = %id, %instance_id, sender = ?sender, "Returning NotFound to upstream");
                            new_state = None;
                            return_msg = Some(GetMsg::Response {
                                id,
                                instance_id,
                                result: GetMsgResult::NotFound,
                            });
                        }
                        _ => return Err(OpError::invalid_transition(self.id)),
                    };
                }
                GetMsg::Response {
                    id,
                    result:
                        GetMsgResult::Found {
                            key,
                            value:
                                StoreResponse {
                                    state: Some(value),
                                    contract,
                                },
                        },
                    ..
                } => {
                    let id = *id;
                    let key = *key;

                    // Use sender_from_addr for logging (optional - sender may not be in ring)
                    let sender = sender_from_addr.clone();

                    tracing::info!(tx = %id, contract = %key, sender = ?sender, state = ?self.state, phase = "response", "GET Response received with state");

                    // Check if contract is required
                    let require_contract = matches!(
                        self.state,
                        Some(GetState::AwaitingResponse(AwaitingResponseData {
                            fetch_contract: true,
                            ..
                        }))
                    );

                    // Get requester and current_hop from current state
                    let (requester, current_hop) =
                        if let Some(GetState::AwaitingResponse(data)) = self.state.as_ref() {
                            (data.requester.clone(), Some(data.current_hop))
                        } else {
                            return Err(OpError::UnexpectedOpState);
                        };

                    // Handle case where contract is required but not provided
                    if require_contract && contract.is_none() {
                        if let Some(_requester) = requester {
                            // no contract, consider this like an error ignoring the incoming update value
                            tracing::warn!(
                                tx = %id,
                                sender = ?sender,
                                "Contract not received from peer while required"
                            );

                            tracing::warn!(
                                tx = %id,
                                %key,
                                sender = ?sender,
                                "Contract not received while required, returning response to upstream",
                            );

                            // Forward NotFound to requester (contract was required but not provided)
                            // local_fallback is only for original requester, not for forwarding
                            op_manager
                                .notify_op_change(
                                    NetMessage::from(GetMsg::Response {
                                        id,
                                        instance_id: *key.id(),
                                        result: GetMsgResult::NotFound,
                                    }),
                                    OpEnum::Get(GetOp {
                                        id,
                                        state: self.state,
                                        result: None,
                                        stats,
                                        upstream_addr: self.upstream_addr,
                                        local_fallback: None,
                                        auto_fetch: false,
                                        ack_received: false,
                                        speculative_paths: 0,
                                    }),
                                )
                                .await?;
                            return Err(OpError::StatePushed);
                        }
                    }

                    // Check if this is the original requester (no upstream to forward to)
                    let is_original_requester = self.upstream_addr.is_none();

                    // Check if subscription was requested
                    let (subscribe_requested, blocking_sub) =
                        if let Some(GetState::AwaitingResponse(data)) = &self.state {
                            (data.subscribe, data.blocking_subscribe)
                        } else {
                            (false, false)
                        };

                    // Always cache contracts we encounter - LRU will handle eviction
                    let should_put = true;

                    // Put contract locally if needed
                    if should_put {
                        // First check if the local state matches the incoming state
                        // to avoid triggering validation errors in contracts that implement
                        // idempotency checks in their update_state() method (issue #2018)
                        let local_state = op_manager
                            .notify_contract_handler(ContractHandlerEvent::GetQuery {
                                instance_id: *key.id(),
                                return_contract_code: false,
                            })
                            .await;

                        let state_matches = match local_state {
                            Ok(ContractHandlerEvent::GetResponse {
                                response:
                                    Ok(StoreResponse {
                                        state: Some(local), ..
                                    }),
                                ..
                            }) => {
                                // Compare the actual state bytes
                                local.as_ref() == value.as_ref()
                            }
                            _ => false, // No local state or error - we should try to cache
                        };

                        if state_matches {
                            tracing::debug!(
                                tx = %id,
                                %key,
                                "Local state matches network state, skipping redundant cache"
                            );

                            // BUG FIX (2026-01): ALWAYS refresh hosting status on GET.
                            // Previously, we only recorded access if !is_hosting_contract(),
                            // which meant re-GETs on cached contracts wouldn't refresh the
                            // hosting cache's TTL/LRU position, causing subscriptions to expire.
                            //
                            // record_get_access now returns is_new atomically, eliminating the
                            // TOCTOU race that existed when checking is_hosting_contract() first.
                            let access_result =
                                op_manager.ring.record_get_access(key, value.size() as u64);

                            // Clean up interest tracking for evicted contracts (always, even if already hosting)
                            let mut removed_contracts = Vec::new();
                            for evicted_key in &access_result.evicted {
                                if op_manager
                                    .interest_manager
                                    .unregister_local_hosting(evicted_key)
                                {
                                    removed_contracts.push(*evicted_key);
                                }
                            }

                            // Only do first-time hosting setup if newly hosting
                            if access_result.is_new {
                                tracing::debug!(tx = %id, %key, "Contract newly hosted");
                                super::announce_contract_hosted(op_manager, &key).await;

                                // Register local interest for delta-based sync
                                let became_interested =
                                    op_manager.interest_manager.register_local_hosting(&key);

                                // Broadcast interest changes to peers
                                let added = if became_interested { vec![key] } else { vec![] };
                                if !added.is_empty() || !removed_contracts.is_empty() {
                                    super::broadcast_change_interests(
                                        op_manager,
                                        added,
                                        removed_contracts,
                                    )
                                    .await;
                                }
                            } else {
                                tracing::debug!(tx = %id, %key, "Refreshed hosting status for already-hosted contract");
                                // Still broadcast eviction changes if any contracts were evicted
                                if !removed_contracts.is_empty() {
                                    super::broadcast_change_interests(
                                        op_manager,
                                        vec![],
                                        removed_contracts,
                                    )
                                    .await;
                                }
                            }

                            // Auto-subscribe to receive updates for this contract.
                            // Only the original requester subscribes — relay peers cache
                            // for durability but don't subscribe (no freshness obligation).
                            if crate::ring::AUTO_SUBSCRIBE_ON_GET && is_original_requester {
                                // Only start new subscription if not already subscribed
                                if access_result.is_new || !op_manager.ring.is_subscribed(&key) {
                                    let blocking = subscribe_requested && blocking_sub;
                                    let child_tx = super::start_subscription_request(
                                        op_manager, id, key, blocking,
                                    );
                                    tracing::debug!(tx = %id, %child_tx, %blocking, "started subscription");
                                }
                            }
                        } else {
                            // Only attempt to cache if we have the contract code.
                            // Without the code, we can't store the contract locally (issue #2306).
                            if contract.is_some() {
                                tracing::debug!(tx = %id, %key, %is_original_requester, %subscribe_requested, "Putting contract at executor - state differs from local cache");
                                let res = op_manager
                                    .notify_contract_handler(ContractHandlerEvent::PutQuery {
                                        key,
                                        state: value.clone(),
                                        related_contracts: RelatedContracts::default(), // fixme: i think we need to get the related contracts so the final put is ok
                                        contract: contract.clone(),
                                    })
                                    .await?;

                                match res {
                                    ContractHandlerEvent::PutResponse {
                                        new_value: Ok(_), ..
                                    } => {
                                        tracing::debug!(tx = %id, %key, "Contract put at executor");

                                        // BUG FIX (2026-01): ALWAYS refresh hosting status on GET.
                                        // This ensures re-GETs keep the hosting cache's TTL/LRU fresh.
                                        //
                                        // record_get_access now returns is_new atomically, eliminating the
                                        // TOCTOU race that existed when checking is_hosting_contract() first.
                                        tracing::debug!(tx = %id, %key, peer = ?op_manager.ring.connection_manager.get_own_addr(), "Recording contract access in hosting cache");
                                        let access_result = op_manager
                                            .ring
                                            .record_get_access(key, value.size() as u64);

                                        // Clean up interest tracking for evicted contracts (always, even if already hosting)
                                        let mut removed_contracts = Vec::new();
                                        for evicted_key in &access_result.evicted {
                                            if op_manager
                                                .interest_manager
                                                .unregister_local_hosting(evicted_key)
                                            {
                                                removed_contracts.push(*evicted_key);
                                            }
                                        }

                                        // Only do first-time hosting setup if newly hosting
                                        if access_result.is_new {
                                            super::announce_contract_hosted(op_manager, &key).await;

                                            // Register local interest for delta-based sync
                                            let became_interested = op_manager
                                                .interest_manager
                                                .register_local_hosting(&key);

                                            // Broadcast interest changes to peers
                                            let added =
                                                if became_interested { vec![key] } else { vec![] };
                                            if !added.is_empty() || !removed_contracts.is_empty() {
                                                super::broadcast_change_interests(
                                                    op_manager,
                                                    added,
                                                    removed_contracts,
                                                )
                                                .await;
                                            }
                                        } else {
                                            tracing::debug!(tx = %id, %key, "Refreshed hosting status for already-hosted contract");
                                            // Still broadcast eviction changes if any contracts were evicted
                                            if !removed_contracts.is_empty() {
                                                super::broadcast_change_interests(
                                                    op_manager,
                                                    vec![],
                                                    removed_contracts,
                                                )
                                                .await;
                                            }
                                        }

                                        // Auto-subscribe to receive updates for this contract.
                                        // Only the original requester subscribes — relay peers cache
                                        // for durability but don't subscribe (no freshness obligation).
                                        if crate::ring::AUTO_SUBSCRIBE_ON_GET
                                            && is_original_requester
                                        {
                                            // Only start new subscription if not already subscribed
                                            if access_result.is_new
                                                || !op_manager.ring.is_subscribed(&key)
                                            {
                                                let blocking = subscribe_requested && blocking_sub;
                                                let child_tx = super::start_subscription_request(
                                                    op_manager, id, key, blocking,
                                                );
                                                tracing::debug!(tx = %id, %child_tx, %blocking, "started subscription");
                                            }
                                        }
                                    }
                                    ContractHandlerEvent::PutResponse {
                                        new_value: Err(err),
                                        ..
                                    } => {
                                        // Local caching failed, but GET operation succeeded
                                        // Log warning and continue - caching is an optimization, not required
                                        tracing::warn!(
                                            tx = %id,
                                            %key,
                                            error = %err,
                                            %is_original_requester,
                                            "Failed to cache contract locally during GET - continuing with operation"
                                        );
                                        // Don't return error - the GET succeeded, caching is optional
                                        // Continue to process the GET result below
                                    }
                                    ContractHandlerEvent::DelegateRequest { .. }
                                    | ContractHandlerEvent::DelegateResponse(_)
                                    | ContractHandlerEvent::PutQuery { .. }
                                    | ContractHandlerEvent::GetQuery { .. }
                                    | ContractHandlerEvent::GetResponse { .. }
                                    | ContractHandlerEvent::UpdateQuery { .. }
                                    | ContractHandlerEvent::UpdateResponse { .. }
                                    | ContractHandlerEvent::UpdateNoChange { .. }
                                    | ContractHandlerEvent::RegisterSubscriberListener { .. }
                                    | ContractHandlerEvent::RegisterSubscriberListenerResponse
                                    | ContractHandlerEvent::QuerySubscriptions { .. }
                                    | ContractHandlerEvent::QuerySubscriptionsResponse
                                    | ContractHandlerEvent::GetSummaryQuery { .. }
                                    | ContractHandlerEvent::GetSummaryResponse { .. }
                                    | ContractHandlerEvent::GetDeltaQuery { .. }
                                    | ContractHandlerEvent::GetDeltaResponse { .. }
                                    | ContractHandlerEvent::NotifySubscriptionError { .. }
                                    | ContractHandlerEvent::NotifySubscriptionErrorResponse
                                    | ContractHandlerEvent::ClientDisconnect { .. } => {
                                        unreachable!(
                                            "PutQuery from Get operation should always return PutResponse"
                                        )
                                    }
                                }
                            } else {
                                // No contract code in GET response - can't cache or subscribe locally.
                                // Without the contract code, we can't:
                                // 1. Validate incoming state updates
                                // 2. Process delta updates from subscriptions
                                // Announcing as cached or subscribing would cause #2306 errors when
                                // updates arrive for a contract we can't process.
                                tracing::warn!(
                                    tx = %id,
                                    %key,
                                    "Cannot cache or subscribe to contract - no contract code in GET response"
                                );
                                // Don't announce cached or start subscription without contract code.
                                // The GET still succeeded - the client gets their state response.
                            }
                        }
                    }

                    // Process based on whether we're originator or forwarding
                    // Use upstream_addr for routing decision (not requester which can fail for transient connections)
                    // First validate we're in an expected state
                    match &self.state {
                        Some(GetState::AwaitingResponse(_)) | Some(GetState::ReceivedRequest) => {}
                        Some(other) => {
                            // Can't take ownership, so format the state for error reporting
                            return Err(OpError::invalid_transition_with_state(
                                self.id,
                                Box::new(format!("{}", other)),
                            ));
                        }
                        None => return Err(OpError::invalid_transition(self.id)),
                    }

                    // Now handle based on upstream_addr
                    if self.upstream_addr.is_none() {
                        // Original requester, operation completed successfully
                        tracing::info!(tx = %id, contract = %key, phase = "complete", "Get response received for contract at original requester");

                        // Emit get_success telemetry (only if sender is known)
                        let hop_count =
                            current_hop.map(|h| op_manager.ring.max_hops_to_live.saturating_sub(h));
                        let hash = Some(state_hash_full(value));
                        if let Some(sender_peer) = sender {
                            if let Some(event) = NetEventLog::get_success(
                                &id,
                                &op_manager.ring,
                                key,
                                sender_peer,
                                hop_count,
                                hash,
                            ) {
                                op_manager.ring.register_events(Either::Left(event)).await;
                            }
                        }

                        new_state = Some(GetState::Finished(FinishedData { key }));
                        return_msg = None;
                        result = Some(GetResult {
                            key,
                            state: value.clone(),
                            contract: contract.clone(),
                        });
                    } else {
                        // Forward response to upstream. Opportunistically cache contract
                        // code so this relay peer can serve future GET requests with
                        // fetch_contract=true. We don't call announce_contract_hosted()
                        // here because relay peers should not advertise contracts they
                        // are not responsible for in the ring.
                        tracing::info!(tx = %id, contract = %key, phase = "response", "Get response received for contract at hop peer");
                        if let Some(code) = contract {
                            if !op_manager.ring.is_hosting_contract(&key) {
                                let om = op_manager.clone();
                                let cache_key = key;
                                let v = value.clone();
                                let c = code.clone();
                                GlobalExecutor::spawn(async move {
                                    let key_str = cache_key.to_string();
                                    let cached = matches!(
                                        om.notify_contract_handler(
                                            ContractHandlerEvent::PutQuery {
                                                key: cache_key,
                                                state: v,
                                                related_contracts: RelatedContracts::default(),
                                                contract: Some(c),
                                            }
                                        )
                                        .await,
                                        Ok(ContractHandlerEvent::PutResponse {
                                            new_value: Ok(_),
                                            ..
                                        })
                                    );
                                    tracing::info!(
                                        contract = %key_str,
                                        phase = "relay_cache",
                                        cached,
                                        "Relay peer contract code cache attempt"
                                    );
                                });
                            }
                        }
                        new_state = None;
                        // Check if the response payload exceeds the streaming
                        // threshold.  When it does, convert to ResponseStreaming
                        // so that upstream relays can use pipe_stream instead of
                        // serial store-and-forward (which adds 10-50 s per hop
                        // for large contracts like the River UI at ~814 KB).
                        let store_response = StoreResponse {
                            state: Some(value.clone()),
                            contract: contract.clone(),
                        };
                        let includes_contract = store_response.contract.is_some();
                        let payload = GetStreamingPayload {
                            key,
                            value: store_response,
                        };
                        let payload_bytes = bincode::serialize(&payload).map_err(|e| {
                            OpError::NotificationChannelError(format!(
                                "Failed to serialize streaming payload: {e}"
                            ))
                        })?;
                        let payload_size = payload_bytes.len();
                        if should_use_streaming(op_manager.streaming_threshold, payload_size) {
                            let sid = StreamId::next_operations();
                            tracing::info!(
                                tx = %id,
                                stream_id = %sid,
                                payload_size,
                                phase = "relay_streaming_forward",
                                "Relay converting non-streaming GET response to streaming for upstream"
                            );
                            return_msg = Some(GetMsg::ResponseStreaming {
                                id,
                                instance_id: *payload.key.id(),
                                stream_id: sid,
                                key: payload.key,
                                total_size: payload_size as u64,
                                includes_contract,
                            });
                            stream_data = Some((sid, bytes::Bytes::from(payload_bytes)));
                        } else {
                            return_msg = Some(GetMsg::Response {
                                id,
                                instance_id: *payload.key.id(),
                                result: GetMsgResult::Found {
                                    key: payload.key,
                                    value: payload.value,
                                },
                            });
                        }
                        tracing::debug!(tx = %id, %key, upstream = ?self.upstream_addr, "Returning contract to upstream");
                        result = Some(GetResult {
                            key,
                            state: value.clone(),
                            contract: contract.clone(),
                        });
                    }
                }
                // DEFENSIVE HANDLING: Found response with empty state
                //
                // This case should not occur in normal operation because:
                // 1. Contracts are always stored with their state
                // 2. If a peer has the contract, it should have state data
                //
                // However, we handle this defensively to avoid undefined behavior if:
                // - A malformed response is received from a peer
                // - There's a race condition during contract storage
                //
                // We treat this as NotFound because a Found response without usable
                // state data is equivalent to not finding the contract.
                GetMsg::Response {
                    id,
                    instance_id,
                    result:
                        GetMsgResult::Found {
                            value: StoreResponse { state: None, .. },
                            ..
                        },
                } => {
                    let id = *id;
                    let instance_id = *instance_id;

                    // Use sender_from_addr for logging (optional - sender may not be in ring)
                    let sender = sender_from_addr.clone();

                    tracing::warn!(
                        tx = %id,
                        %instance_id,
                        sender = ?sender,
                        phase = "response",
                        "GET Found response with empty state - treating as NotFound"
                    );

                    // Forward as NotFound since Found with empty state isn't useful
                    if self.upstream_addr.is_some() {
                        return_msg = Some(GetMsg::Response {
                            id,
                            instance_id,
                            result: GetMsgResult::NotFound,
                        });
                        new_state = None;
                    } else {
                        // Original requester - operation failed
                        return_msg = None;
                        new_state = None;
                        // result remains None to indicate failure
                    }
                }

                // Streaming GET response handler
                GetMsg::ResponseStreaming {
                    id: msg_id,
                    instance_id,
                    stream_id,
                    key,
                    total_size,
                    includes_contract,
                } => {
                    let id = *msg_id;
                    let key = *key;
                    let stream_id = *stream_id;
                    let includes_contract = *includes_contract;

                    tracing::info!(
                        tx = %id,
                        %instance_id,
                        contract = %key,
                        stream_id = %stream_id,
                        total_size,
                        includes_contract,
                        phase = "streaming_response",
                        "Processing GET ResponseStreaming"
                    );

                    // Step 1: Claim the stream from orphan registry (atomic dedup)
                    let peer_addr = match source_addr {
                        Some(addr) => addr,
                        None => {
                            tracing::error!(tx = %id, "source_addr missing for streaming GET response");
                            return Err(OpError::UnexpectedOpState);
                        }
                    };
                    let stream_handle = match op_manager
                        .orphan_stream_registry()
                        .claim_or_wait(peer_addr, stream_id, STREAM_CLAIM_TIMEOUT)
                        .await
                    {
                        Ok(handle) => handle,
                        Err(OrphanStreamError::AlreadyClaimed) => {
                            tracing::debug!(
                                tx = %id,
                                stream_id = %stream_id,
                                "GET ResponseStreaming skipped — stream already claimed (dedup)"
                            );
                            // Push the operation state back since load_or_init popped it.
                            // Without this, duplicate metadata messages (from embedded fragment #1)
                            // permanently lose the operation state, preventing subsequent
                            // ResponseStreaming from being matched to the operation.
                            if self.state.is_some() {
                                if let Err(e) = op_manager
                                    .push(
                                        id,
                                        OpEnum::Get(GetOp {
                                            id,
                                            state: self.state,
                                            result: self.result,
                                            stats,
                                            upstream_addr: self.upstream_addr,
                                            local_fallback,
                                            auto_fetch: false,
                                            ack_received: false,
                                            speculative_paths: 0,
                                        }),
                                    )
                                    .await
                                {
                                    tracing::warn!(tx = %id, error = %e, "failed to push GET op state back after dedup");
                                }
                            }
                            return Err(OpError::OpNotPresent(id));
                        }
                        Err(e) => {
                            tracing::error!(
                                tx = %id,
                                stream_id = %stream_id,
                                error = %e,
                                "Failed to claim stream from orphan registry"
                            );
                            // Push the operation state back to prevent loss
                            if self.state.is_some() {
                                if let Err(e) = op_manager
                                    .push(
                                        id,
                                        OpEnum::Get(GetOp {
                                            id,
                                            state: self.state,
                                            result: self.result,
                                            stats,
                                            upstream_addr: self.upstream_addr,
                                            local_fallback,
                                            auto_fetch: false,
                                            ack_received: false,
                                            speculative_paths: 0,
                                        }),
                                    )
                                    .await
                                {
                                    tracing::warn!(tx = %id, error = %e, "failed to push GET op state back after orphan claim failure");
                                }
                            }
                            return Err(OpError::OrphanStreamClaimFailed);
                        }
                    };

                    // Step 2: Check if we should pipe upstream BEFORE assembly
                    // This enables low-latency forwarding of responses
                    let is_original_requester = self.upstream_addr.is_none();

                    // Extract subscription flags from state (needed for auto-subscribe after caching)
                    let (subscribe_requested, blocking_sub) =
                        if let Some(GetState::AwaitingResponse(data)) = &self.state {
                            (data.subscribe, data.blocking_subscribe)
                        } else {
                            (false, false)
                        };
                    let piping_started = if !is_original_requester {
                        let upstream_addr = self
                            .upstream_addr
                            .expect("non-originator must have upstream");
                        // Check if streaming should be used based on the original stream size
                        if should_use_streaming(
                            op_manager.streaming_threshold,
                            *total_size as usize,
                        ) {
                            let outbound_sid = StreamId::next_operations();
                            let forked_handle = stream_handle.fork();

                            tracing::info!(
                                tx = %id,
                                inbound_stream_id = %stream_id,
                                outbound_stream_id = %outbound_sid,
                                total_size,
                                peer_addr = %upstream_addr,
                                "Starting piped stream forwarding of GET response to upstream"
                            );

                            // Send metadata message first
                            let pipe_metadata = GetMsg::ResponseStreaming {
                                id,
                                instance_id: *instance_id,
                                stream_id: outbound_sid,
                                key,
                                total_size: *total_size,
                                includes_contract,
                            };
                            let pipe_metadata_net: NetMessage = pipe_metadata.into();
                            // Serialize metadata for embedding in fragment #1 (fix #2757)
                            let embedded_metadata = match bincode::serialize(&pipe_metadata_net) {
                                Ok(bytes) => Some(bytes::Bytes::from(bytes)),
                                Err(e) => {
                                    tracing::warn!(
                                        tx = %id,
                                        error = %e,
                                        "Failed to serialize piped stream metadata for embedding"
                                    );
                                    None
                                }
                            };
                            conn_manager.send(upstream_addr, pipe_metadata_net).await?;

                            // Start piping (runs asynchronously in background)
                            conn_manager
                                .pipe_stream(
                                    upstream_addr,
                                    outbound_sid,
                                    forked_handle,
                                    embedded_metadata,
                                )
                                .await?;

                            true
                        } else {
                            false
                        }
                    } else {
                        false
                    };

                    // Step 3: Wait for stream to complete and assemble data (for local caching)
                    let stream_data = match stream_handle.assemble().await {
                        Ok(data) => data,
                        Err(e) => {
                            tracing::error!(
                                tx = %id,
                                stream_id = %stream_id,
                                error = %e,
                                "Failed to assemble stream data"
                            );
                            return Err(OpError::StreamCancelled);
                        }
                    };

                    tracing::debug!(
                        tx = %id,
                        stream_id = %stream_id,
                        received_size = stream_data.len(),
                        expected_size = total_size,
                        "Stream data assembled"
                    );

                    // Step 3: Deserialize the streaming payload
                    let payload: messages::GetStreamingPayload =
                        match bincode::deserialize(&stream_data) {
                            Ok(p) => p,
                            Err(e) => {
                                tracing::error!(
                                    tx = %id,
                                    stream_id = %stream_id,
                                    error = %e,
                                    "Failed to deserialize streaming payload"
                                );
                                return Err(OpError::invalid_transition(self.id));
                            }
                        };

                    // Verify key matches
                    if payload.key != key {
                        tracing::error!(
                            tx = %id,
                            expected = %key,
                            actual = %payload.key,
                            "Contract key mismatch in streaming payload"
                        );
                        return Err(OpError::invalid_transition(self.id));
                    }

                    let value = payload.value;

                    // Get current hop for telemetry
                    let current_hop = if let Some(GetState::AwaitingResponse(data)) = &self.state {
                        let current_hop = &data.current_hop;
                        Some(*current_hop)
                    } else {
                        None
                    };

                    // Step 5: Cache the contract locally, announce hosting, and auto-subscribe.
                    // This mirrors the non-streaming Response path — without it, the node
                    // never registers as subscribed after a streaming GET, causing every
                    // subsequent GET to hit the network instead of serving from local cache.
                    if let Some(state) = &value.state {
                        let contract_to_cache = if includes_contract {
                            value.contract.clone()
                        } else {
                            None
                        };

                        // Record access atomically — returns whether this is a newly-hosted contract
                        let access_result =
                            op_manager.ring.record_get_access(key, state.size() as u64);

                        // Clean up interest tracking for evicted contracts
                        let mut removed_contracts = Vec::new();
                        for evicted_key in &access_result.evicted {
                            if op_manager
                                .interest_manager
                                .unregister_local_hosting(evicted_key)
                            {
                                removed_contracts.push(*evicted_key);
                            }
                        }

                        if access_result.is_new {
                            // First time hosting — cache the contract, then announce only on success.
                            // Mirrors the non-streaming "state differs" path which gates announce
                            // on PutResponse { new_value: Ok(_) }.
                            let put_ok = match op_manager
                                .notify_contract_handler(ContractHandlerEvent::PutQuery {
                                    key,
                                    state: state.clone(),
                                    related_contracts: RelatedContracts::default(),
                                    contract: contract_to_cache,
                                })
                                .await
                            {
                                Ok(ContractHandlerEvent::PutResponse {
                                    new_value: Ok(_), ..
                                }) => true,
                                Ok(ContractHandlerEvent::PutResponse {
                                    new_value: Err(err),
                                    ..
                                }) => {
                                    tracing::warn!(
                                        tx = %id, contract = %key, error = %err,
                                        "Streaming GET: PutQuery rejected by executor"
                                    );
                                    false
                                }
                                Ok(other) => {
                                    tracing::warn!(
                                        tx = %id, contract = %key,
                                        response = %other,
                                        "Streaming GET: unexpected PutQuery response"
                                    );
                                    false
                                }
                                Err(e) => {
                                    tracing::warn!(
                                        contract = %key, error = %e,
                                        "failed to cache contract via PutQuery"
                                    );
                                    false
                                }
                            };

                            if put_ok {
                                tracing::debug!(tx = %id, %key, "Contract newly hosted (streaming)");
                                super::announce_contract_hosted(op_manager, &key).await;

                                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() {
                                    super::broadcast_change_interests(
                                        op_manager,
                                        added,
                                        removed_contracts,
                                    )
                                    .await;
                                }

                                // Auto-subscribe only if we successfully cached the contract.
                                if crate::ring::AUTO_SUBSCRIBE_ON_GET
                                    && is_original_requester
                                    && !op_manager.ring.is_subscribed(&key)
                                {
                                    let blocking = subscribe_requested && blocking_sub;
                                    let child_tx = super::start_subscription_request(
                                        op_manager, id, key, blocking,
                                    );
                                    tracing::debug!(tx = %id, %child_tx, %blocking, "started subscription (streaming)");
                                }
                            } else if !removed_contracts.is_empty() {
                                super::broadcast_change_interests(
                                    op_manager,
                                    vec![],
                                    removed_contracts,
                                )
                                .await;
                            }
                        } else {
                            // Already hosting — refresh state (fire-and-forget since we already
                            // have a valid cached copy; failure just means we keep the old state).
                            if let Err(e) = op_manager
                                .notify_contract_handler(ContractHandlerEvent::PutQuery {
                                    key,
                                    state: state.clone(),
                                    related_contracts: RelatedContracts::default(),
                                    contract: contract_to_cache,
                                })
                                .await
                            {
                                tracing::warn!(contract = %key, error = %e, "failed to refresh contract state via PutQuery");
                            }

                            tracing::debug!(tx = %id, %key, "Refreshed hosting status for already-hosted contract (streaming)");
                            if !removed_contracts.is_empty() {
                                super::broadcast_change_interests(
                                    op_manager,
                                    vec![],
                                    removed_contracts,
                                )
                                .await;
                            }

                            // Auto-subscribe for already-hosted contracts that lost their subscription.
                            if crate::ring::AUTO_SUBSCRIBE_ON_GET
                                && is_original_requester
                                && !op_manager.ring.is_subscribed(&key)
                            {
                                let blocking = subscribe_requested && blocking_sub;
                                let child_tx = super::start_subscription_request(
                                    op_manager, id, key, blocking,
                                );
                                tracing::debug!(tx = %id, %child_tx, %blocking, "started subscription (streaming, re-subscribe)");
                            }
                        }
                    }

                    // Step 6: Emit telemetry
                    let hop_count =
                        current_hop.map(|h| op_manager.ring.max_hops_to_live.saturating_sub(h));
                    let hash = value.state.as_ref().map(state_hash_full);
                    if let Some(event) = NetEventLog::get_success(
                        &id,
                        &op_manager.ring,
                        key,
                        op_manager.ring.connection_manager.own_location(),
                        hop_count,
                        hash,
                    ) {
                        op_manager.ring.register_events(Either::Left(event)).await;
                    }

                    // Step 7: Build result and determine response
                    if is_original_requester {
                        // This is the original requester - operation complete
                        tracing::info!(
                            tx = %id,
                            contract = %key,
                            phase = "complete",
                            "Streaming GET complete (originator)"
                        );

                        // State must be present for a successful GET
                        let state = match value.state {
                            Some(s) => s,
                            None => {
                                tracing::error!(
                                    tx = %id,
                                    contract = %key,
                                    "Streaming GET response has no state"
                                );
                                return Err(OpError::invalid_transition(self.id));
                            }
                        };

                        result = Some(GetResult {
                            key,
                            state,
                            contract: value.contract,
                        });
                        new_state = Some(GetState::Finished(FinishedData { key }));
                        return_msg = None;
                    } else if piping_started {
                        // Piping is already underway - no need to send return_msg
                        tracing::debug!(
                            tx = %id,
                            contract = %key,
                            phase = "forward",
                            "GET response piping in progress to upstream"
                        );
                        return_msg = None;
                        new_state = None;
                    } else {
                        // Forward the response to upstream as a regular Response
                        // (streaming not used - payload below threshold)
                        tracing::debug!(
                            tx = %id,
                            contract = %key,
                            phase = "forward",
                            "Forwarding GET response as non-streaming to upstream"
                        );

                        return_msg = Some(GetMsg::Response {
                            id,
                            instance_id: *instance_id,
                            result: GetMsgResult::Found { key, value },
                        });
                        new_state = None;
                    }
                }

                // Streaming GET response acknowledgment handler
                GetMsg::ResponseStreamingAck {
                    id: msg_id,
                    stream_id,
                } => {
                    let id = *msg_id;
                    let stream_id = *stream_id;

                    // The acknowledgment confirms the stream was received.
                    // For now, we just log it and clean up.
                    tracing::info!(
                        tx = %id,
                        stream_id = %stream_id,
                        phase = "streaming_ack",
                        "Streaming GET response acknowledged"
                    );
                    new_state = None;
                    return_msg = None;
                }
                GetMsg::ForwardingAck { id, instance_id } => {
                    // A downstream relay has acknowledged forwarding our request.
                    // Mark the op so the GC task knows the chain is alive.
                    tracing::debug!(
                        tx = %id,
                        %instance_id,
                        "Received forwarding ACK from downstream relay"
                    );

                    // Emit telemetry for ForwardingAck received (#3570 diagnostics)
                    if let Some(event) = NetEventLog::get_forwarding_ack_received(
                        &self.id,
                        &op_manager.ring,
                        *instance_id,
                    ) {
                        op_manager.ring.register_events(Either::Left(event)).await;
                    }

                    return Ok(OperationResult::ContinueOp(OpEnum::Get(GetOp {
                        id: self.id,
                        state: self.state,
                        result: self.result,
                        stats,
                        upstream_addr: self.upstream_addr,
                        local_fallback,
                        auto_fetch,
                        ack_received: true,
                        speculative_paths: self.speculative_paths,
                    })));
                }
            }

            build_op_result(GetOpResult {
                id: self.id,
                state: new_state,
                msg: return_msg,
                result,
                stats,
                upstream_addr: self.upstream_addr,
                auto_fetch,
                stream_data,
                local_fallback,
            })
        })
    }
}

/// Build a `GetMsg::Response` with `Found` result from a local fallback cache entry.
fn build_fallback_found_response(
    id: Transaction,
    instance_id: ContractInstanceId,
    key: ContractKey,
    state: WrappedState,
    contract: Option<ContractContainer>,
) -> GetMsg {
    GetMsg::Response {
        id,
        instance_id,
        result: GetMsgResult::Found {
            key,
            value: StoreResponse {
                state: Some(state),
                contract,
            },
        },
    }
}

struct GetOpResult {
    id: Transaction,
    state: Option<GetState>,
    msg: Option<GetMsg>,
    result: Option<GetResult>,
    stats: Option<Box<GetStats>>,
    upstream_addr: Option<std::net::SocketAddr>,
    auto_fetch: bool,
    stream_data: Option<(StreamId, bytes::Bytes)>,
    local_fallback: Option<(ContractKey, WrappedState, Option<ContractContainer>)>,
}

fn build_op_result(params: GetOpResult) -> Result<OperationResult, OpError> {
    let GetOpResult {
        id,
        state,
        msg,
        result,
        stats,
        upstream_addr,
        auto_fetch,
        stream_data,
        local_fallback,
    } = params;
    // Determine the next hop for sending the message:
    // - For Response messages: route back to upstream_addr (who sent us the request)
    // - For Request messages being forwarded: use next_hop from state
    let next_hop = match (&msg, &state) {
        (Some(GetMsg::Response { .. }) | Some(GetMsg::ResponseStreaming { .. }), _) => {
            upstream_addr
        }
        (Some(GetMsg::Request { .. }), Some(GetState::AwaitingResponse(data))) => {
            data.next_hop.socket_addr()
        }
        _ => None,
    };

    let output_op = state.map(|state| GetOp {
        id,
        state: Some(state),
        result,
        stats,
        upstream_addr,
        local_fallback,
        auto_fetch,
        ack_received: false,
        speculative_paths: 0,
    });
    let return_msg = msg.map(NetMessage::from);
    let op_state = output_op.map(OpEnum::Get);
    Ok(match (return_msg, op_state) {
        (Some(msg), Some(state)) => OperationResult::SendAndContinue {
            msg,
            next_hop,
            state,
            stream_data,
        },
        (Some(msg), None) => OperationResult::SendAndComplete {
            msg,
            next_hop,
            stream_data,
        },
        (None, Some(state)) => OperationResult::ContinueOp(state),
        (None, None) => OperationResult::Completed,
    })
}

#[allow(clippy::too_many_arguments)]
async fn try_forward_or_return(
    id: Transaction,
    instance_id: ContractInstanceId,
    (htl, fetch_contract): (usize, bool),
    (this_peer, sender): (PeerKeyLocation, Option<PeerKeyLocation>),
    visited: super::VisitedPeers,
    op_manager: &OpManager,
    stats: Option<Box<GetStats>>,
    upstream_addr: Option<std::net::SocketAddr>,
    local_fallback: Option<(ContractKey, WrappedState, Option<ContractContainer>)>,
) -> Result<OperationResult, OpError> {
    tracing::warn!(
        tx = %id,
        %instance_id,
        peer_addr = %this_peer,
        sender = ?sender,
        phase = "forward",
        "Contract not found while processing a get request"
    );

    let mut new_visited = visited.clone();
    if let Some(addr) = this_peer.socket_addr() {
        new_visited.mark_visited(addr);
    }

    let new_htl = htl.saturating_sub(1);

    let (new_target, alternatives) = if new_htl == 0 {
        tracing::warn!(
            tx = %id,
            sender = ?sender,
            htl = 0,
            phase = "error",
            "The maximum hops have been exceeded, sending response back to the node"
        );
        (None, vec![])
    } else {
        let mut candidates = op_manager.ring.k_closest_potentially_hosting(
            &instance_id,
            &new_visited,
            DEFAULT_MAX_BREADTH,
        );

        if candidates.is_empty() {
            tracing::warn!(
                tx = %id,
                %instance_id,
                peer_addr = %this_peer,
                phase = "error",
                "No other peers found while trying to get the contract"
            );
            (None, vec![])
        } else {
            let target = candidates.remove(0);
            (Some(target), candidates)
        }
    };

    if let Some(target) = new_target {
        tracing::debug!(
            tx = %id,
            "Forwarding get request to {}",
            target
        );

        // Emit telemetry: relay is forwarding GET to next hop
        if let Some(event) =
            NetEventLog::get_request(&id, &op_manager.ring, instance_id, target.clone(), new_htl)
        {
            op_manager.ring.register_events(Either::Left(event)).await;
        }

        let mut tried_peers = HashSet::new();
        if let Some(addr) = target.socket_addr() {
            tried_peers.insert(addr);
        }

        // Forwarding nodes always use non-blocking subscriptions:
        // blocking_subscribe is a client-side preference that only
        // applies to the originator node.
        build_op_result(GetOpResult {
            id,
            state: Some(GetState::AwaitingResponse(AwaitingResponseData {
                instance_id,
                requester: sender,
                retries: 0,
                fetch_contract,
                current_hop: new_htl,
                subscribe: false,
                blocking_subscribe: false,
                next_hop: target.clone(),
                tried_peers,
                alternatives,
                attempts_at_hop: 1,
                visited: new_visited.clone(),
            })),
            msg: Some(GetMsg::Request {
                id,
                instance_id,
                fetch_contract,
                htl: new_htl,
                visited: new_visited,
            }),
            result: None,
            // Track the forward target so timeouts report to
            // PeerHealthTracker and the failure estimator (#3527).
            stats: stats.map(|mut s| {
                s.next_peer = Some(target.clone());
                s
            }),
            upstream_addr,
            stream_data: None,
            local_fallback,
            auto_fetch: false,
        })
    } else if upstream_addr.is_some() {
        // No targets found — check for local fallback before returning NotFound
        if let Some((key, state, contract)) = local_fallback {
            tracing::info!(
                tx = %id,
                contract = %key,
                "Relay serving local cache as fallback (no forwarding targets)"
            );
            let msg = build_fallback_found_response(id, instance_id, key, state, contract);
            build_op_result(GetOpResult {
                id,
                state: None,
                msg: Some(msg),
                result: None,
                stats,
                upstream_addr,
                stream_data: None,
                local_fallback: None,
                auto_fetch: false,
            })
        } else {
            tracing::warn!(
                tx = %id,
                %instance_id,
                phase = "not_found",
                "No peers to forward get request to, returning NotFound to upstream"
            );
            // Emit telemetry: relay returning NotFound (no forwarding targets)
            if let Some(event) =
                NetEventLog::get_not_found(&id, &op_manager.ring, instance_id, None)
            {
                op_manager.ring.register_events(Either::Left(event)).await;
            }
            build_op_result(GetOpResult {
                id,
                state: None,
                msg: Some(GetMsg::Response {
                    id,
                    instance_id,
                    result: GetMsgResult::NotFound,
                }),
                result: None,
                stats,
                upstream_addr,
                stream_data: None,
                local_fallback: None,
                auto_fetch: false,
            })
        }
    } else {
        // Original requester with no forwarding targets - operation fails locally
        tracing::warn!(
            tx = %id,
            %instance_id,
            phase = "not_found",
            "No peers to forward get request to and no upstream - local operation fails"
        );

        notify_get_failed(
            op_manager,
            id,
            &format!("contract {instance_id} not found, no peers available to forward"),
        );

        build_op_result(GetOpResult {
            id,
            state: None,
            msg: None,
            result: None,
            stats,
            upstream_addr,
            stream_data: None,
            local_fallback: None,
            auto_fetch: false,
        })
    }
}

impl IsOperationCompleted for GetOp {
    fn is_completed(&self) -> bool {
        matches!(self.state, Some(GetState::Finished(_)))
    }
}

/// Notify the client that a GET operation failed with the given reason.
fn notify_get_failed(op_manager: &OpManager, tx: Transaction, reason: &str) {
    op_manager.send_client_result(
        tx,
        Err(ErrorKind::OperationError {
            cause: reason.to_string().into(),
        }
        .into()),
    );
}

mod messages {
    use std::fmt::Display;

    use serde::{Deserialize, Serialize};

    use super::*;
    use crate::transport::peer_connection::StreamId;

    /// Payload for streaming GET responses.
    /// Contains the result of a GET operation, serialized for streaming transfer.
    #[derive(Debug, Serialize, Deserialize)]
    pub(crate) struct GetStreamingPayload {
        pub key: ContractKey,
        pub value: StoreResponse,
    }

    /// Result of a GET operation - either the contract was found or it wasn't.
    ///
    /// This provides explicit semantics for "contract not found" rather than
    /// requiring interpretation of empty responses or timeouts.
    #[derive(Debug, Serialize, Deserialize, Clone)]
    pub(crate) enum GetMsgResult {
        /// Contract was found - includes full key and value
        Found {
            key: ContractKey,
            value: StoreResponse,
        },
        /// Contract was not found after exhaustive search
        NotFound,
    }

    /// GET operation messages.
    ///
    /// Uses hop-by-hop routing: each node stores `upstream_addr` from the transport layer
    /// to route responses back. No `PeerKeyLocation` is embedded in wire messages.
    #[derive(Debug, Serialize, Deserialize, Clone)]
    pub(crate) enum GetMsg {
        /// Request to retrieve a contract. Forwarded hop-by-hop toward contract location.
        /// Uses instance_id since the requester may not have the full key yet.
        Request {
            id: Transaction,
            instance_id: ContractInstanceId,
            fetch_contract: bool,
            /// Hops to live - decremented at each hop. When 0, stop forwarding.
            htl: usize,
            /// Bloom filter tracking visited peers to prevent loops.
            visited: super::super::VisitedPeers,
        },
        /// Response for a GET operation. Routed hop-by-hop back to originator.
        /// Uses instance_id for routing (always available from the request).
        /// The full ContractKey is only present in GetMsgResult::Found.
        Response {
            id: Transaction,
            instance_id: ContractInstanceId,
            result: GetMsgResult,
        },

        /// Streaming response for large contract data. Used when the response payload
        /// exceeds streaming_threshold (default 64KB). The actual data is sent via
        /// a separate stream identified by stream_id.
        ///
        /// This variant is only used when streaming is enabled in config.
        ResponseStreaming {
            id: Transaction,
            instance_id: ContractInstanceId,
            /// Identifies the stream carrying the response data
            stream_id: StreamId,
            /// Full contract key (known since we found the contract)
            key: ContractKey,
            /// Total size of the streamed payload in bytes
            total_size: u64,
            /// Whether the response includes the contract code (not just state)
            includes_contract: bool,
        },

        /// Acknowledgment that a streaming response was received.
        /// Sent back to the responder to confirm stream completion.
        ResponseStreamingAck {
            id: Transaction,
            stream_id: StreamId,
        },

        /// Lightweight ACK sent by a relay peer back to its upstream when it forwards
        /// a GET request to the next hop. Tells the upstream "I'm working on it" so
        /// the GC task can distinguish dead peers from slow multi-hop chains.
        /// Fire-and-forget — no response expected.
        ForwardingAck {
            id: Transaction,
            instance_id: ContractInstanceId,
        },
    }

    impl InnerMessage for GetMsg {
        fn id(&self) -> &Transaction {
            match self {
                Self::Request { id, .. }
                | Self::Response { id, .. }
                | Self::ResponseStreaming { id, .. }
                | Self::ResponseStreamingAck { id, .. }
                | Self::ForwardingAck { id, .. } => id,
            }
        }

        fn requested_location(&self) -> Option<Location> {
            match self {
                Self::Request { instance_id, .. }
                | Self::Response { instance_id, .. }
                | Self::ResponseStreaming { instance_id, .. }
                | Self::ForwardingAck { instance_id, .. } => Some(Location::from(instance_id)),
                Self::ResponseStreamingAck { .. } => {
                    // Ack doesn't carry location info - routed via stream_id
                    None
                }
            }
        }
    }

    impl Display for GetMsg {
        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            let id = self.id();
            match self {
                Self::Request {
                    instance_id, htl, ..
                } => {
                    write!(
                        f,
                        "Get::Request(id: {id}, instance_id: {instance_id}, htl: {htl})"
                    )
                }
                Self::Response {
                    instance_id,
                    result,
                    ..
                } => {
                    let result_str = match result {
                        GetMsgResult::Found { key, .. } => format!("Found({key})"),
                        GetMsgResult::NotFound => "NotFound".to_string(),
                    };
                    write!(
                        f,
                        "Get::Response(id: {id}, instance_id: {instance_id}, result: {result_str})"
                    )
                }
                Self::ResponseStreaming {
                    instance_id,
                    stream_id,
                    key,
                    total_size,
                    ..
                } => {
                    write!(
                        f,
                        "Get::ResponseStreaming(id: {id}, instance_id: {instance_id}, key: {key}, stream: {stream_id}, size: {total_size})"
                    )
                }
                Self::ResponseStreamingAck { stream_id, .. } => {
                    write!(
                        f,
                        "Get::ResponseStreamingAck(id: {id}, stream: {stream_id})"
                    )
                }
                Self::ForwardingAck { instance_id, .. } => {
                    write!(
                        f,
                        "Get::ForwardingAck(id: {id}, instance_id: {instance_id})"
                    )
                }
            }
        }
    }
}

#[cfg(test)]
#[allow(clippy::wildcard_enum_match_arm)]
mod tests {
    use super::*;
    use crate::message::Transaction;
    use crate::operations::VisitedPeers;
    use crate::operations::test_utils::make_contract_key;

    fn make_get_op(state: Option<GetState>, result: Option<GetResult>) -> GetOp {
        GetOp {
            id: Transaction::new::<GetMsg>(),
            state,
            result,
            stats: None,
            upstream_addr: None,
            local_fallback: None,
            auto_fetch: false,
            ack_received: false,
            speculative_paths: 0,
        }
    }

    // Tests for finalized() method
    #[test]
    fn get_op_finalized_when_finished_with_result() {
        let key = make_contract_key(1);
        let result = GetResult {
            key,
            state: WrappedState::new(vec![1, 2, 3]),
            contract: None,
        };
        let op = make_get_op(Some(GetState::Finished(FinishedData { key })), Some(result));
        assert!(
            op.finalized(),
            "GetOp should be finalized when state is Finished and result is present"
        );
    }

    #[test]
    fn get_op_not_finalized_when_finished_without_result() {
        let key = make_contract_key(1);
        let op = make_get_op(Some(GetState::Finished(FinishedData { key })), None);
        assert!(
            !op.finalized(),
            "GetOp should not be finalized when state is Finished but result is None"
        );
    }

    #[test]
    fn get_op_not_finalized_when_received_request() {
        let op = make_get_op(Some(GetState::ReceivedRequest), None);
        assert!(
            !op.finalized(),
            "GetOp should not be finalized in ReceivedRequest state"
        );
    }

    #[test]
    fn get_op_not_finalized_when_state_is_none() {
        let op = make_get_op(None, None);
        assert!(
            !op.finalized(),
            "GetOp should not be finalized when state is None"
        );
    }

    // Tests for to_host_result() method
    #[test]
    fn get_op_to_host_result_success_when_result_present() {
        let key = make_contract_key(1);
        let state_data = WrappedState::new(vec![1, 2, 3]);
        let result = GetResult {
            key,
            state: state_data.clone(),
            contract: None,
        };
        let op = make_get_op(Some(GetState::Finished(FinishedData { key })), Some(result));
        let host_result = op.to_host_result();

        assert!(
            host_result.is_ok(),
            "to_host_result should return Ok when result is present"
        );

        if let Ok(HostResponse::ContractResponse(
            freenet_stdlib::client_api::ContractResponse::GetResponse {
                key: returned_key,
                state: returned_state,
                ..
            },
        )) = host_result
        {
            assert_eq!(returned_key, key, "Returned key should match");
            assert_eq!(returned_state, state_data, "Returned state should match");
        } else {
            panic!("Expected GetResponse");
        }
    }

    #[test]
    fn get_op_to_host_result_error_when_no_result() {
        let op = make_get_op(Some(GetState::ReceivedRequest), None);
        let result = op.to_host_result();
        assert!(
            result.is_err(),
            "to_host_result should return Err when result is None"
        );
    }

    // Tests for outcome() method - partial coverage since full stats require complex setup
    #[test]
    fn get_op_outcome_incomplete_without_stats() {
        let key = make_contract_key(1);
        let result = GetResult {
            key,
            state: WrappedState::new(vec![]),
            contract: None,
        };
        let op = make_get_op(Some(GetState::Finished(FinishedData { key })), Some(result));
        let outcome = op.outcome();

        assert!(matches!(outcome, OpOutcome::Incomplete));
    }

    // Tests for GetMsg helper methods
    #[test]
    fn get_msg_id_returns_transaction() {
        let tx = Transaction::new::<GetMsg>();
        let msg = GetMsg::Request {
            id: tx,
            instance_id: *make_contract_key(1).id(),
            fetch_contract: false,
            htl: 5,
            visited: VisitedPeers::new(&tx),
        };
        assert_eq!(*msg.id(), tx, "id() should return the transaction ID");
    }

    #[test]
    fn get_msg_display_formats_correctly() {
        let tx = Transaction::new::<GetMsg>();
        let msg = GetMsg::Request {
            id: tx,
            instance_id: *make_contract_key(1).id(),
            fetch_contract: false,
            htl: 5,
            visited: VisitedPeers::new(&tx),
        };
        let display = format!("{}", msg);
        assert!(
            display.contains("Request"),
            "Display should contain message type name"
        );
    }

    // Tests for GetState Display
    #[test]
    fn get_state_display_received_request() {
        let state = GetState::ReceivedRequest;
        let display = format!("{}", state);
        assert!(
            display.contains("ReceivedRequest"),
            "Display should contain state name"
        );
    }

    #[test]
    fn get_state_display_finished() {
        let state = GetState::Finished(FinishedData {
            key: make_contract_key(1),
        });
        let display = format!("{}", state);
        assert!(
            display.contains("Finished"),
            "Display should contain state name"
        );
    }

    #[test]
    fn get_msg_response_found_display_formats_correctly() {
        let tx = Transaction::new::<GetMsg>();
        let key = make_contract_key(1);
        let msg = GetMsg::Response {
            id: tx,
            instance_id: *key.id(),
            result: GetMsgResult::Found {
                key,
                value: StoreResponse {
                    state: Some(WrappedState::new(vec![1, 2, 3])),
                    contract: None,
                },
            },
        };
        let display = format!("{}", msg);
        assert!(
            display.contains("Response"),
            "Display should contain message type name"
        );
        assert!(
            display.contains("Found"),
            "Display should indicate Found result"
        );
    }

    #[test]
    fn get_msg_response_notfound_display_formats_correctly() {
        let tx = Transaction::new::<GetMsg>();
        let instance_id = *make_contract_key(1).id();
        let msg = GetMsg::Response {
            id: tx,
            instance_id,
            result: GetMsgResult::NotFound,
        };
        let display = format!("{}", msg);
        assert!(
            display.contains("Response"),
            "Display should contain message type name"
        );
        assert!(
            display.contains("NotFound"),
            "Display should indicate NotFound result"
        );
    }

    #[test]
    fn get_msg_result_found_contains_key_and_value() {
        let key = make_contract_key(1);
        let state = WrappedState::new(vec![1, 2, 3]);
        let result = GetMsgResult::Found {
            key,
            value: StoreResponse {
                state: Some(state.clone()),
                contract: None,
            },
        };
        if let GetMsgResult::Found {
            key: found_key,
            value,
        } = result
        {
            assert_eq!(found_key, key);
            assert_eq!(value.state, Some(state));
        } else {
            panic!("Expected Found variant");
        }
    }

    #[test]
    fn get_msg_result_notfound_is_unit_variant() {
        let result = GetMsgResult::NotFound;
        assert!(
            matches!(result, GetMsgResult::NotFound),
            "NotFound should match NotFound"
        );
    }

    #[test]
    fn get_msg_response_requested_location_uses_instance_id() {
        let tx = Transaction::new::<GetMsg>();
        let key = make_contract_key(1);
        let instance_id = *key.id();

        // Test Found variant
        let msg_found = GetMsg::Response {
            id: tx,
            instance_id,
            result: GetMsgResult::Found {
                key,
                value: StoreResponse {
                    state: Some(WrappedState::new(vec![])),
                    contract: None,
                },
            },
        };
        let location_found = msg_found.requested_location();
        assert!(
            location_found.is_some(),
            "Response should have a requested location"
        );
        assert_eq!(
            location_found.unwrap(),
            Location::from(&instance_id),
            "Location should be derived from instance_id"
        );

        // Test NotFound variant
        let msg_notfound = GetMsg::Response {
            id: tx,
            instance_id,
            result: GetMsgResult::NotFound,
        };
        let location_notfound = msg_notfound.requested_location();
        assert!(
            location_notfound.is_some(),
            "NotFound Response should have a requested location"
        );
        assert_eq!(
            location_notfound.unwrap(),
            Location::from(&instance_id),
            "Location should be derived from instance_id for NotFound too"
        );
    }

    // Tests for blocking_subscribe propagation
    #[test]
    fn start_op_propagates_blocking_subscribe_true() {
        let instance_id = ContractInstanceId::new([1u8; 32]);
        let op = start_op(instance_id, true, true, true);
        match op.state {
            Some(GetState::PrepareRequest(data)) => {
                let blocking_subscribe = data.blocking_subscribe;
                assert!(
                    blocking_subscribe,
                    "blocking_subscribe should be true in PrepareRequest"
                );
            }
            other => panic!("Expected PrepareRequest state, got {:?}", other),
        }
    }

    #[test]
    fn start_op_with_id_propagates_blocking_subscribe_true() {
        let instance_id = ContractInstanceId::new([1u8; 32]);
        let tx = Transaction::new::<GetMsg>();
        let op = start_op_with_id(instance_id, true, true, true, tx);
        match op.state {
            Some(GetState::PrepareRequest(data)) => {
                let blocking_subscribe = data.blocking_subscribe;
                assert!(
                    blocking_subscribe,
                    "blocking_subscribe should be true in PrepareRequest via start_op_with_id"
                );
            }
            other => panic!("Expected PrepareRequest state, got {:?}", other),
        }
    }

    #[test]
    fn start_op_defaults_blocking_subscribe_false() {
        let instance_id = ContractInstanceId::new([1u8; 32]);
        let op = start_op(instance_id, true, true, false);
        match op.state {
            Some(GetState::PrepareRequest(data)) => {
                let blocking_subscribe = data.blocking_subscribe;
                assert!(
                    !blocking_subscribe,
                    "blocking_subscribe should be false by default"
                );
            }
            other => panic!("Expected PrepareRequest state, got {:?}", other),
        }
    }

    #[test]
    fn test_failure_outcome_for_get() {
        use crate::ring::{Location, PeerKeyLocation};
        use std::time::Duration;

        let target_peer = PeerKeyLocation::random();
        let contract_location = Location::random();

        // GetOp with stats but no result → should return ContractOpFailure
        let op = GetOp {
            id: Transaction::new::<GetMsg>(),
            state: None,
            result: None,
            stats: Some(Box::new(GetStats {
                next_peer: Some(target_peer.clone()),
                contract_location,
                first_response_time: None,
                transfer_time: None,
            })),
            upstream_addr: None,
            local_fallback: None,
            auto_fetch: false,
            ack_received: false,
            speculative_paths: 0,
        };

        match op.outcome() {
            OpOutcome::ContractOpFailure {
                target_peer: peer,
                contract_location: loc,
            } => {
                assert_eq!(*peer, target_peer);
                assert_eq!(loc, contract_location);
            }
            OpOutcome::ContractOpSuccess { .. }
            | OpOutcome::ContractOpSuccessUntimed { .. }
            | OpOutcome::Incomplete
            | OpOutcome::Irrelevant => panic!("Expected ContractOpFailure"),
        }

        // GetOp with no stats and no result → should return Incomplete
        let op_no_stats = GetOp {
            id: Transaction::new::<GetMsg>(),
            state: None,
            result: None,
            stats: None,
            upstream_addr: None,
            local_fallback: None,
            auto_fetch: false,
            ack_received: false,
            speculative_paths: 0,
        };
        assert!(
            matches!(op_no_stats.outcome(), OpOutcome::Incomplete),
            "GetOp with no stats should return Incomplete"
        );

        // GetOp with result + complete stats → should return ContractOpSuccess
        let now = Instant::now();
        let later = now + Duration::from_millis(50);
        let op_success = GetOp {
            id: Transaction::new::<GetMsg>(),
            state: None,
            result: Some(GetResult {
                key: make_contract_key(1),
                state: WrappedState::new(vec![1, 2, 3]),
                contract: None,
            }),
            stats: Some(Box::new(GetStats {
                next_peer: Some(target_peer.clone()),
                contract_location,
                first_response_time: Some((now, Some(later))),
                transfer_time: Some((now, Some(later))),
            })),
            upstream_addr: None,
            local_fallback: None,
            auto_fetch: false,
            ack_received: false,
            speculative_paths: 0,
        };
        assert!(
            matches!(op_success.outcome(), OpOutcome::ContractOpSuccess { .. }),
            "GetOp with result and complete stats should return ContractOpSuccess"
        );
    }

    // ============ Partial timing outcome tests (validates GET partial timing fix) ============

    /// Result + target_peer but incomplete timing → ContractOpSuccessUntimed.
    /// Before the fix, this returned Incomplete, so the router never got feedback.
    #[test]
    fn test_get_outcome_success_untimed_partial_timing() {
        use crate::ring::{Location, PeerKeyLocation};

        let target_peer = PeerKeyLocation::random();
        let contract_location = Location::random();
        let now = Instant::now();

        // Result present, target_peer set, first_response_time has start but no end
        let op = GetOp {
            id: Transaction::new::<GetMsg>(),
            state: Some(GetState::Finished(FinishedData {
                key: make_contract_key(1),
            })),
            result: Some(GetResult {
                key: make_contract_key(1),
                state: WrappedState::new(vec![1, 2, 3]),
                contract: None,
            }),
            stats: Some(Box::new(GetStats {
                next_peer: Some(target_peer.clone()),
                contract_location,
                first_response_time: Some((now, None)), // Started but not completed
                transfer_time: Some((now, None)),       // Started but not completed
            })),
            upstream_addr: None,
            local_fallback: None,
            auto_fetch: false,
            ack_received: false,
            speculative_paths: 0,
        };

        match op.outcome() {
            OpOutcome::ContractOpSuccessUntimed {
                target_peer: peer,
                contract_location: loc,
            } => {
                assert_eq!(*peer, target_peer);
                assert_eq!(loc, contract_location);
            }
            other @ OpOutcome::ContractOpSuccess { .. }
            | other @ OpOutcome::ContractOpFailure { .. }
            | other @ OpOutcome::Incomplete
            | other @ OpOutcome::Irrelevant => {
                panic!("Expected ContractOpSuccessUntimed, got {other:?}")
            }
        }
    }

    /// Result + target_peer but no transfer_time at all → ContractOpSuccessUntimed.
    #[test]
    fn test_get_outcome_success_untimed_no_transfer_time() {
        use crate::ring::{Location, PeerKeyLocation};

        let target_peer = PeerKeyLocation::random();
        let contract_location = Location::random();

        let op = GetOp {
            id: Transaction::new::<GetMsg>(),
            state: Some(GetState::Finished(FinishedData {
                key: make_contract_key(1),
            })),
            result: Some(GetResult {
                key: make_contract_key(1),
                state: WrappedState::new(vec![1, 2, 3]),
                contract: None,
            }),
            stats: Some(Box::new(GetStats {
                next_peer: Some(target_peer.clone()),
                contract_location,
                first_response_time: None,
                transfer_time: None,
            })),
            upstream_addr: None,
            local_fallback: None,
            auto_fetch: false,
            ack_received: false,
            speculative_paths: 0,
        };

        match op.outcome() {
            OpOutcome::ContractOpSuccessUntimed {
                target_peer: peer,
                contract_location: loc,
            } => {
                assert_eq!(*peer, target_peer);
                assert_eq!(loc, contract_location);
            }
            other @ OpOutcome::ContractOpSuccess { .. }
            | other @ OpOutcome::ContractOpFailure { .. }
            | other @ OpOutcome::Incomplete
            | other @ OpOutcome::Irrelevant => {
                panic!("Expected ContractOpSuccessUntimed, got {other:?}")
            }
        }
    }

    /// Result but no target_peer → Incomplete (can't attribute to a peer).
    #[test]
    fn test_get_outcome_incomplete_result_no_peer() {
        let op = GetOp {
            id: Transaction::new::<GetMsg>(),
            state: Some(GetState::Finished(FinishedData {
                key: make_contract_key(1),
            })),
            result: Some(GetResult {
                key: make_contract_key(1),
                state: WrappedState::new(vec![1, 2, 3]),
                contract: None,
            }),
            stats: Some(Box::new(GetStats {
                next_peer: None,
                contract_location: Location::random(),
                first_response_time: None,
                transfer_time: None,
            })),
            upstream_addr: None,
            local_fallback: None,
            auto_fetch: false,
            ack_received: false,
            speculative_paths: 0,
        };

        assert!(
            matches!(op.outcome(), OpOutcome::Incomplete),
            "Result with no target_peer should return Incomplete"
        );
    }

    /// No result + partial timing → still ContractOpFailure (regression guard).
    #[test]
    fn test_get_outcome_failure_no_result_partial_timing() {
        use crate::ring::{Location, PeerKeyLocation};

        let target_peer = PeerKeyLocation::random();
        let contract_location = Location::random();
        let now = Instant::now();

        let op = GetOp {
            id: Transaction::new::<GetMsg>(),
            state: None,
            result: None,
            stats: Some(Box::new(GetStats {
                next_peer: Some(target_peer.clone()),
                contract_location,
                first_response_time: Some((now, None)),
                transfer_time: None,
            })),
            upstream_addr: None,
            local_fallback: None,
            auto_fetch: false,
            ack_received: false,
            speculative_paths: 0,
        };

        match op.outcome() {
            OpOutcome::ContractOpFailure {
                target_peer: peer,
                contract_location: loc,
            } => {
                assert_eq!(*peer, target_peer);
                assert_eq!(loc, contract_location);
            }
            other @ OpOutcome::ContractOpSuccess { .. }
            | other @ OpOutcome::ContractOpSuccessUntimed { .. }
            | other @ OpOutcome::Incomplete
            | other @ OpOutcome::Irrelevant => panic!("Expected ContractOpFailure, got {other:?}"),
        }
    }

    #[test]
    fn test_build_fallback_found_response() {
        let id = Transaction::new::<GetMsg>();
        let key = make_contract_key(1);
        let instance_id = *key.id();
        let state = WrappedState::new(vec![1, 2, 3]);
        let msg = build_fallback_found_response(id, instance_id, key, state.clone(), None);
        match msg {
            GetMsg::Response {
                id: resp_id,
                instance_id: resp_iid,
                result: GetMsgResult::Found { key: k, value },
            } => {
                assert_eq!(resp_id, id);
                assert_eq!(resp_iid, instance_id);
                assert_eq!(k, key);
                assert_eq!(value.state, Some(state));
                assert!(value.contract.is_none());
            }
            other @ GetMsg::Request { .. }
            | other @ GetMsg::Response { .. }
            | other @ GetMsg::ResponseStreaming { .. }
            | other @ GetMsg::ResponseStreamingAck { .. }
            | other @ GetMsg::ForwardingAck { .. } => {
                panic!("Expected Found response, got {other:?}")
            }
        }
    }

    // === Tests for retry_with_next_alternative ===

    use crate::operations::test_utils::make_peer;

    fn make_awaiting_op(alternatives: Vec<PeerKeyLocation>, tried: &[PeerKeyLocation]) -> GetOp {
        let id = Transaction::new::<GetMsg>();
        let instance_id = ContractInstanceId::new([42u8; 32]);
        let visited = VisitedPeers::new(&id);
        let next_hop = make_peer(9000);
        let mut tried_peers = HashSet::new();
        for p in tried {
            if let Some(addr) = p.socket_addr() {
                tried_peers.insert(addr);
            }
        }
        if let Some(addr) = next_hop.socket_addr() {
            tried_peers.insert(addr);
        }
        GetOp {
            id,
            state: Some(GetState::AwaitingResponse(AwaitingResponseData {
                instance_id,
                retries: 0,
                fetch_contract: true,
                requester: None,
                current_hop: 7,
                subscribe: false,
                blocking_subscribe: false,
                next_hop,
                tried_peers,
                alternatives,
                attempts_at_hop: 1,
                visited,
            })),
            result: None,
            stats: None,
            upstream_addr: None,
            local_fallback: None,
            auto_fetch: false,
            ack_received: false,
            speculative_paths: 0,
        }
    }

    #[test]
    fn retry_with_local_alternative_succeeds() {
        let alt1 = make_peer(1001);
        let alt2 = make_peer(1002);
        let op = make_awaiting_op(vec![alt1.clone(), alt2], &[]);

        let result = op.retry_with_next_alternative(7, &[]);
        assert!(result.is_ok(), "Should succeed with local alternatives");

        let (new_op, msg) = result.unwrap_or_else(|_| panic!("expected Ok"));
        // The message should be a Request preserving original fetch_contract
        match &msg {
            GetMsg::Request { fetch_contract, .. } => {
                assert!(
                    *fetch_contract,
                    "retry must preserve original fetch_contract"
                );
            }
            GetMsg::Response { .. }
            | GetMsg::ResponseStreaming { .. }
            | GetMsg::ResponseStreamingAck { .. }
            | GetMsg::ForwardingAck { .. } => panic!("Expected GetMsg::Request"),
        }
        // Should have 1 alternative remaining
        if let Some(GetState::AwaitingResponse(data)) = &new_op.state {
            assert_eq!(data.alternatives.len(), 1);
            assert!(data.tried_peers.contains(&alt1.socket_addr().unwrap()));
        } else {
            panic!("Expected AwaitingResponse state");
        }
    }

    #[test]
    fn retry_exhausted_returns_err() {
        let op = make_awaiting_op(vec![], &[]);

        let result = op.retry_with_next_alternative(7, &[]);
        assert!(result.is_err(), "Should fail with no alternatives");

        // Verify op is returned intact
        let returned_op = match result {
            Err(op) => *op,
            Ok(_) => panic!("expected Err"),
        };
        assert!(
            matches!(&returned_op.state, Some(GetState::AwaitingResponse(_))),
            "State should be preserved"
        );
    }

    #[test]
    fn retry_dbf_fallback_injects_new_peers() {
        // No local alternatives, but provide fallback peers
        let fallback1 = make_peer(2001);
        let fallback2 = make_peer(2002);
        let op = make_awaiting_op(vec![], &[]);

        let result = op.retry_with_next_alternative(7, &[fallback1.clone(), fallback2]);
        assert!(result.is_ok(), "Should succeed with DBF fallback peers");

        let (new_op, _msg) = result.unwrap_or_else(|_| panic!("expected Ok"));
        if let Some(GetState::AwaitingResponse(data)) = &new_op.state {
            // One fallback used as next_hop, one remaining
            assert_eq!(data.alternatives.len(), 1);
            assert!(data.tried_peers.contains(&fallback1.socket_addr().unwrap()));
        } else {
            panic!("Expected AwaitingResponse state");
        }
    }

    #[test]
    fn retry_dbf_fallback_skips_already_tried() {
        let already_tried = make_peer(3001);
        let fresh_peer = make_peer(3002);
        let op = make_awaiting_op(vec![], std::slice::from_ref(&already_tried));

        let result = op.retry_with_next_alternative(7, &[already_tried, fresh_peer.clone()]);
        assert!(result.is_ok(), "Should find fresh_peer");

        let (new_op, _msg) = result.unwrap_or_else(|_| panic!("expected Ok"));
        if let Some(GetState::AwaitingResponse(data)) = &new_op.state {
            assert_eq!(data.alternatives.len(), 0, "Only one fresh peer injected");
            assert!(
                data.tried_peers
                    .contains(&fresh_peer.socket_addr().unwrap())
            );
        } else {
            panic!("Expected AwaitingResponse state");
        }
    }

    #[test]
    fn retry_dbf_all_tried_returns_err() {
        let tried1 = make_peer(4001);
        let tried2 = make_peer(4002);
        let op = make_awaiting_op(vec![], &[tried1.clone(), tried2.clone()]);

        let result = op.retry_with_next_alternative(7, &[tried1, tried2]);
        assert!(result.is_err(), "All fallback peers already tried");
    }

    /// Verify that retry HTL decreases with each attempt (#3570).
    ///
    /// At the originator, current_hop == max_hops_to_live, so the old code
    /// (htl: max_hops_to_live) always sent full-depth retries. The fix divides
    /// HTL by attempts_at_hop, creating progressively shorter retry chains.
    #[test]
    fn retry_htl_decreases_with_attempts() {
        let alt1 = make_peer(6001);
        let alt2 = make_peer(6002);
        let alt3 = make_peer(6003);
        let op = make_awaiting_op(vec![alt1, alt2, alt3], &[]);

        // make_awaiting_op sets attempts_at_hop=1, then retry increments to 2 before computing HTL.
        // First retry: attempts_at_hop becomes 2 → 10/2 = 5
        let (op, msg) = op
            .retry_with_next_alternative(10, &[])
            .unwrap_or_else(|_| panic!("retry 1 failed"));
        match &msg {
            GetMsg::Request { htl, .. } => {
                assert_eq!(
                    *htl, 5,
                    "First retry: 10/2=5 (attempts_at_hop incremented to 2)"
                );
            }
            other @ GetMsg::Response { .. }
            | other @ GetMsg::ResponseStreaming { .. }
            | other @ GetMsg::ResponseStreamingAck { .. }
            | other @ GetMsg::ForwardingAck { .. } => {
                panic!("Expected Request, got {other}")
            }
        }

        // Second retry: attempts_at_hop becomes 3 → 10/3 = 3
        let (op, msg) = op
            .retry_with_next_alternative(10, &[])
            .unwrap_or_else(|_| panic!("retry 2 failed"));
        match &msg {
            GetMsg::Request { htl, .. } => {
                assert_eq!(
                    *htl, MIN_RETRY_HTL,
                    "Second retry: 10/3=3 (clamped to MIN_RETRY_HTL)"
                );
            }
            other @ GetMsg::Response { .. }
            | other @ GetMsg::ResponseStreaming { .. }
            | other @ GetMsg::ResponseStreamingAck { .. }
            | other @ GetMsg::ForwardingAck { .. } => {
                panic!("Expected Request, got {other}")
            }
        }

        // Third retry: attempts_at_hop becomes 4 → 10/4 = 2 → clamped to MIN_RETRY_HTL=3
        let (_op, msg) = op
            .retry_with_next_alternative(10, &[])
            .unwrap_or_else(|_| panic!("retry 3 failed"));
        match &msg {
            GetMsg::Request { htl, .. } => {
                assert_eq!(
                    *htl, MIN_RETRY_HTL,
                    "Third retry: 10/4=2 → clamped to MIN_RETRY_HTL"
                );
            }
            other @ GetMsg::Response { .. }
            | other @ GetMsg::ResponseStreaming { .. }
            | other @ GetMsg::ResponseStreamingAck { .. }
            | other @ GetMsg::ForwardingAck { .. } => {
                panic!("Expected Request, got {other}")
            }
        }
    }

    /// Verify that MIN_RETRY_HTL floor is applied even when max_htl is low.
    #[test]
    fn retry_htl_floor_at_min() {
        let alt = make_peer(7001);
        let mut op = make_awaiting_op(vec![alt], &[]);
        // Simulate many attempts to push HTL below floor
        if let Some(GetState::AwaitingResponse(ref mut data)) = op.state {
            data.attempts_at_hop = 20;
        }

        let (_op, msg) = op
            .retry_with_next_alternative(10, &[])
            .unwrap_or_else(|_| panic!("retry failed"));
        match &msg {
            GetMsg::Request { htl, .. } => {
                assert!(
                    *htl >= MIN_RETRY_HTL,
                    "HTL {} should not fall below MIN_RETRY_HTL {}",
                    htl,
                    MIN_RETRY_HTL
                );
            }
            other @ GetMsg::Response { .. }
            | other @ GetMsg::ResponseStreaming { .. }
            | other @ GetMsg::ResponseStreamingAck { .. }
            | other @ GetMsg::ForwardingAck { .. } => {
                panic!("Expected Request, got {other}")
            }
        }
    }

    /// Verify that bloom-filter-visited peers are excluded from fallback injection (#3570).
    #[test]
    fn retry_dbf_fallback_skips_bloom_visited() {
        let visited_peer = make_peer(8001);
        let fresh_peer = make_peer(8002);

        // Create op with the visited peer marked in the bloom filter
        let mut op = make_awaiting_op(vec![], &[]);
        if let Some(GetState::AwaitingResponse(ref mut data)) = op.state {
            if let Some(addr) = visited_peer.socket_addr() {
                data.visited.mark_visited(addr);
            }
            // Remove visited_peer from tried_peers so only bloom filter catches it
            if let Some(addr) = visited_peer.socket_addr() {
                data.tried_peers.remove(&addr);
            }
        }

        let result = op.retry_with_next_alternative(7, &[visited_peer.clone(), fresh_peer.clone()]);
        assert!(
            result.is_ok(),
            "Should find fresh_peer despite visited_peer in bloom"
        );

        let (new_op, _msg) = result.unwrap_or_else(|_| panic!("retry failed"));
        if let Some(GetState::AwaitingResponse(data)) = &new_op.state {
            assert_eq!(
                data.alternatives.len(),
                0,
                "Only fresh_peer should be injected (visited_peer filtered by bloom)"
            );
        } else {
            panic!("Expected AwaitingResponse state");
        }
    }

    /// Verify that retry targets are marked in the bloom filter (#3570).
    #[test]
    fn retry_marks_target_in_bloom_filter() {
        let alt = make_peer(9001);
        let alt_addr = alt.socket_addr().unwrap();
        let op = make_awaiting_op(vec![alt], &[]);

        let (new_op, _msg) = op
            .retry_with_next_alternative(7, &[])
            .unwrap_or_else(|_| panic!("retry failed"));
        if let Some(GetState::AwaitingResponse(data)) = &new_op.state {
            assert!(
                data.visited.probably_visited(alt_addr),
                "Retry target should be marked in bloom filter"
            );
        } else {
            panic!("Expected AwaitingResponse state");
        }
    }

    #[test]
    fn retry_wrong_state_returns_err() {
        // PrepareRequest state
        let op = make_get_op(
            Some(GetState::PrepareRequest(PrepareRequestData {
                instance_id: ContractInstanceId::new([1u8; 32]),
                id: Transaction::new::<GetMsg>(),
                fetch_contract: true,
                subscribe: false,
                blocking_subscribe: false,
            })),
            None,
        );
        assert!(op.retry_with_next_alternative(7, &[]).is_err());

        // ReceivedRequest state
        let op = make_get_op(Some(GetState::ReceivedRequest), None);
        assert!(op.retry_with_next_alternative(7, &[]).is_err());

        // None state
        let op = make_get_op(None, None);
        assert!(op.retry_with_next_alternative(7, &[]).is_err());
    }

    // === Tests for start_targeted_op ===

    #[test]
    fn start_targeted_op_creates_correct_state() {
        let target = make_peer(5001);
        let instance_id = ContractInstanceId::new([99u8; 32]);

        let (op, msg) = start_targeted_op(instance_id, target.clone(), 10);

        // Should be auto_fetch
        assert!(op.auto_fetch, "Targeted op should be marked as auto_fetch");

        // Should be in AwaitingResponse state targeting the peer
        if let Some(GetState::AwaitingResponse(data)) = &op.state {
            assert_eq!(data.instance_id, instance_id);
            assert!(data.fetch_contract);
            assert!(data.requester.is_none());
            assert!(data.tried_peers.contains(&target.socket_addr().unwrap()));
            assert!(data.alternatives.is_empty());
        } else {
            panic!("Expected AwaitingResponse state");
        }

        // Message should be a Request with correct fields
        match msg {
            GetMsg::Request {
                instance_id: msg_id,
                fetch_contract,
                htl,
                ..
            } => {
                assert_eq!(msg_id, instance_id);
                assert!(fetch_contract);
                assert_eq!(htl, 10);
            }
            GetMsg::Response { .. }
            | GetMsg::ResponseStreaming { .. }
            | GetMsg::ResponseStreamingAck { .. }
            | GetMsg::ForwardingAck { .. } => {
                panic!("Expected Request message")
            }
        }
    }

    // === Tests for is_client_initiated ===

    #[test]
    fn is_client_initiated_true_for_prepare_request() {
        let op = make_get_op(
            Some(GetState::PrepareRequest(PrepareRequestData {
                instance_id: ContractInstanceId::new([1u8; 32]),
                id: Transaction::new::<GetMsg>(),
                fetch_contract: true,
                subscribe: false,
                blocking_subscribe: false,
            })),
            None,
        );
        assert!(op.is_client_initiated());
    }

    #[test]
    fn is_client_initiated_true_for_awaiting_no_requester() {
        let op = make_awaiting_op(vec![], &[]);
        assert!(op.is_client_initiated());
    }

    #[test]
    fn is_client_initiated_false_for_awaiting_with_requester() {
        let id = Transaction::new::<GetMsg>();
        let instance_id = ContractInstanceId::new([42u8; 32]);
        let visited = VisitedPeers::new(&id);
        let requester = make_peer(6001);
        let op = GetOp {
            id,
            state: Some(GetState::AwaitingResponse(AwaitingResponseData {
                instance_id,
                retries: 0,
                fetch_contract: true,
                requester: Some(requester),
                current_hop: 7,
                subscribe: false,
                blocking_subscribe: false,
                next_hop: make_peer(6002),
                tried_peers: HashSet::new(),
                alternatives: vec![],
                attempts_at_hop: 1,
                visited,
            })),
            result: None,
            stats: None,
            upstream_addr: None,
            local_fallback: None,
            auto_fetch: false,
            ack_received: false,
            speculative_paths: 0,
        };
        assert!(!op.is_client_initiated());
    }

    #[test]
    fn is_client_initiated_false_for_auto_fetch() {
        let target = make_peer(7001);
        let instance_id = ContractInstanceId::new([77u8; 32]);
        let (op, _msg) = start_targeted_op(instance_id, target, 10);
        // auto_fetch ops should NOT be client-initiated even though requester is None
        assert!(
            !op.is_client_initiated(),
            "Auto-fetch GET should not be client-initiated"
        );
    }

    #[test]
    fn is_client_initiated_false_for_other_states() {
        let op = make_get_op(Some(GetState::ReceivedRequest), None);
        assert!(!op.is_client_initiated());

        let key = make_contract_key(1);
        let op = make_get_op(Some(GetState::Finished(FinishedData { key })), None);
        assert!(!op.is_client_initiated());

        let op = make_get_op(None, None);
        assert!(!op.is_client_initiated());
    }

    // === Tests for GC task retry flow ===
    //
    // These tests reproduce the exact scenario from the garbage_cleanup_task in
    // op_state_manager.rs: a GET op has been stuck for >20s with no response,
    // and the GC task selects it for retry.
    //
    // The GC task uses:
    //   1. tx.elapsed() > GET_RETRY_THRESHOLD (20s ± 20% jitter)
    //   2. retry_with_next_alternative(max_htl, &all_connected)
    //
    // Without the fix (no GC retry logic), stuck GETs would sit until the 60s
    // OPERATION_TTL expires and then be silently removed — no retry, no client
    // notification.

    use crate::config::{GlobalRng, GlobalSimulationTime};

    /// Verify that a transaction created 25s ago would be selected as a
    /// retry candidate by the GC task's threshold check.
    ///
    /// Removing the GC retry logic from op_state_manager.rs would make this
    /// test's scenario moot — the elapsed check would never be performed
    /// and stuck GETs would silently expire.
    #[test]
    fn gc_retry_candidate_selected_after_threshold() {
        // Set deterministic simulation time
        GlobalSimulationTime::set_time_ms(1_700_000_000_000);
        GlobalRng::set_seed(0x6C01);

        // Create a transaction (records creation timestamp via current_time_ms)
        let tx = Transaction::new::<GetMsg>();
        // Advance simulation time by 25 seconds (past the 20s threshold).
        // Creation timestamp is ~1_700_000_000_000 (base + small counter offset).
        GlobalSimulationTime::set_time_ms(1_700_000_000_000 + 25_000);

        let elapsed = tx.elapsed();
        assert!(
            elapsed > std::time::Duration::from_secs(20),
            "Transaction should show >20s elapsed after time advancement, got {:?}",
            elapsed
        );

        // This is what the GC task checks: elapsed > threshold * (retry_count + 1)
        let threshold = std::time::Duration::from_secs(20);
        let retry_count = 0u32;
        let base = threshold * (retry_count + 1);
        // With jitter factor 0.8-1.2, the threshold ranges from 16s to 24s
        // At 25s elapsed, we're past even the worst-case jitter
        assert!(
            elapsed > base.mul_f64(1.2),
            "Should exceed even worst-case jittered threshold"
        );
    }

    /// Verify that a transaction created only 10s ago would NOT be selected
    /// as a retry candidate.
    #[test]
    fn gc_retry_candidate_not_selected_before_threshold() {
        GlobalSimulationTime::set_time_ms(1_700_000_000_000);
        GlobalRng::set_seed(0x6C02);

        let tx = Transaction::new::<GetMsg>();
        // Only 10 seconds — below the 20s threshold
        GlobalSimulationTime::set_time_ms(1_700_000_000_000 + 10_000);

        let elapsed = tx.elapsed();
        assert!(
            elapsed < std::time::Duration::from_secs(20),
            "Transaction should show <20s elapsed, got {:?}",
            elapsed
        );
    }

    /// Full GC retry flow: stuck GET → time passes → retry with alternative.
    ///
    /// Reproduces the exact flow from garbage_cleanup_task:
    ///   1. GET op created, sent to peer, waiting for response
    ///   2. 25 seconds pass with no response
    ///   3. GC task selects it as retry candidate
    ///   4. retry_with_next_alternative produces a new Request message
    ///   5. Op is re-inserted with updated state
    ///
    /// Without the fix: step 4 doesn't exist — the op sits until TTL expiry.
    /// Removing retry_with_next_alternative → this test fails to compile.
    /// Removing the GC retry logic → step 3-5 never happen in production.
    #[test]
    fn gc_retry_full_flow_stuck_get_retries_with_alternative() {
        GlobalSimulationTime::set_time_ms(1_700_000_000_000);
        GlobalRng::set_seed(0x6C03);

        // Create a GET op with 2 alternative peers
        let alt1 = make_peer(4001);
        let alt2 = make_peer(4002);
        let op = make_awaiting_op(vec![alt1.clone(), alt2], &[]);
        let tx = op.id;

        // Simulate the op being stuck: advance time by 25 seconds
        GlobalSimulationTime::set_time_ms(1_700_000_000_000 + 25_000);

        // Verify the GC task would select this as a retry candidate
        assert!(
            tx.elapsed() > std::time::Duration::from_secs(20),
            "Op should be eligible for retry"
        );

        // GC task calls retry_with_next_alternative (this IS the fix)
        let max_htl = 7;
        let all_connected: Vec<PeerKeyLocation> = vec![]; // no DBF needed, has alternatives
        let result = op.retry_with_next_alternative(max_htl, &all_connected);

        // With the fix: produces a retry message targeting alt1
        let (new_op, msg) = result.unwrap_or_else(|_| {
            panic!("GC retry should produce a message when alternatives exist")
        });

        // Verify the retry message uses reduced HTL (not full max_htl).
        // make_awaiting_op sets attempts_at_hop=1, retry increments to 2 → 7/2=3.
        match &msg {
            GetMsg::Request { htl, .. } => {
                assert!(
                    *htl <= max_htl,
                    "Retry HTL ({}) should not exceed max_htl ({})",
                    htl,
                    max_htl
                );
                assert!(
                    *htl >= MIN_RETRY_HTL,
                    "Retry HTL ({}) should be at least MIN_RETRY_HTL ({})",
                    htl,
                    MIN_RETRY_HTL
                );
            }
            GetMsg::Response { .. }
            | GetMsg::ResponseStreaming { .. }
            | GetMsg::ResponseStreamingAck { .. }
            | GetMsg::ForwardingAck { .. } => panic!("Expected Request"),
        }

        // Verify the op state was updated: alt1 is now the next_hop, alt2 remains
        if let Some(GetState::AwaitingResponse(data)) = &new_op.state {
            assert_eq!(
                data.next_hop, alt1,
                "Should be targeting the first alternative"
            );
            assert_eq!(data.alternatives.len(), 1, "One alternative remaining");
            assert!(
                data.tried_peers.contains(&alt1.socket_addr().unwrap()),
                "alt1 should be in tried_peers"
            );
        } else {
            panic!("Expected AwaitingResponse state after retry");
        }
    }

    /// GC retry with DBF fallback: stuck GET, all alternatives exhausted,
    /// broadens search to all connected peers.
    ///
    /// Without the DBF fallback fix: when alternatives are empty, the retry
    /// returns Err and the op stays stuck until TTL expiry.
    /// With the fix: fallback_peers (from ring.get_connections_by_location)
    /// are injected as new alternatives.
    #[test]
    fn gc_retry_dbf_fallback_broadens_to_connected_peers() {
        GlobalSimulationTime::set_time_ms(1_700_000_000_000);
        GlobalRng::set_seed(0x6C04);

        // Create a GET op with NO alternatives (all exhausted)
        let op = make_awaiting_op(vec![], &[]);

        // Without DBF fallback: retry fails (no alternatives)
        let fallback_peers: Vec<PeerKeyLocation> = vec![];
        let op_clone_for_no_fallback = make_awaiting_op(vec![], &[]);
        let result = op_clone_for_no_fallback.retry_with_next_alternative(7, &fallback_peers);
        assert!(result.is_err(), "Without fallback peers, retry should fail");

        // WITH DBF fallback: provide connected peers that haven't been tried
        let fallback1 = make_peer(5001);
        let fallback2 = make_peer(5002);
        let fallback_peers = vec![fallback1.clone(), fallback2];

        let result = op.retry_with_next_alternative(7, &fallback_peers);
        let (new_op, msg) =
            result.unwrap_or_else(|_| panic!("DBF fallback should inject new peers and retry"));

        // Verify the retry targets a fallback peer
        assert!(matches!(msg, GetMsg::Request { .. }));

        if let Some(GetState::AwaitingResponse(data)) = &new_op.state {
            assert!(
                data.tried_peers.contains(&fallback1.socket_addr().unwrap()),
                "Fallback peer should be in tried_peers"
            );
            // One fallback was used, one remains as alternative
            assert_eq!(
                data.alternatives.len(),
                1,
                "Second fallback should remain as alternative"
            );
        } else {
            panic!("Expected AwaitingResponse state");
        }
    }

    /// Verify that successive GC retries advance the threshold multiplicatively.
    ///
    /// The GC task uses: threshold = GET_RETRY_THRESHOLD * (retry_count + 1)
    ///   retry 0: fires at ~20s
    ///   retry 1: fires at ~40s
    ///   retry 2: fires at ~60s (near TTL expiry)
    ///
    /// This prevents rapid-fire retries from overwhelming the network.
    #[test]
    fn gc_retry_threshold_scales_with_retry_count() {
        GlobalSimulationTime::set_time_ms(1_700_000_000_000);
        GlobalRng::set_seed(0x6C05);

        let tx = Transaction::new::<GetMsg>();
        // Transaction was created at ~1_700_000_000_000 (base + tiny counter offset)
        let base_ms = 1_700_000_000_000u64;

        // ACK_TIMEOUT is 3s (matches op_state_manager.rs GC task)
        let threshold = std::time::Duration::from_secs(3);

        // At 4s: retry_count=0 threshold=3s → eligible
        GlobalSimulationTime::set_time_ms(base_ms + 4_000);
        let base_0 = threshold * 1;
        assert!(tx.elapsed() > base_0, "First retry should fire at ~3s");

        // At 4s: retry_count=1 threshold=6s → NOT eligible
        let base_1 = threshold * 2;
        assert!(
            tx.elapsed() < base_1,
            "Second retry should NOT fire at 4s (needs ~6s)"
        );

        // At 7s: retry_count=1 threshold=6s → eligible
        GlobalSimulationTime::set_time_ms(base_ms + 7_000);
        assert!(tx.elapsed() > base_1, "Second retry should fire at ~6s");

        // At 7s: retry_count=2 threshold=9s → NOT eligible
        let base_2 = threshold * 3;
        assert!(
            tx.elapsed() < base_2,
            "Third retry should NOT fire at 7s (needs ~9s)"
        );
    }

    // === Tests for ForwardingAck serde round-trip ===

    #[test]
    fn forwarding_ack_serde_roundtrip() {
        let id = Transaction::new::<GetMsg>();
        let instance_id = ContractInstanceId::new([42; 32]);
        let msg = GetMsg::ForwardingAck { id, instance_id };

        let serialized = bincode::serialize(&msg).expect("serialize");
        let deserialized: GetMsg = bincode::deserialize(&serialized).expect("deserialize");

        match deserialized {
            GetMsg::ForwardingAck {
                id: deser_id,
                instance_id: deser_iid,
            } => {
                assert_eq!(deser_id, id);
                assert_eq!(deser_iid, instance_id);
            }
            other @ GetMsg::Request { .. }
            | other @ GetMsg::Response { .. }
            | other @ GetMsg::ResponseStreaming { .. }
            | other @ GetMsg::ResponseStreamingAck { .. } => {
                panic!("Expected ForwardingAck, got {other}")
            }
        }
    }

    // === Tests for ACK-aware GC retry logic ===
    //
    // These tests replicate the GC task's decision logic from op_state_manager.rs
    // to verify the retry/skip conditions at the unit level.

    /// Helper that replicates the GC task's retry eligibility check for a GET op.
    /// Returns true if the op would be selected as a retry candidate.
    fn gc_would_retry(op: &GetOp, retry_count: usize) -> bool {
        const ACK_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(3);
        const PROGRESS_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(7);
        const MAX_SPECULATIVE_PATHS: u8 = 2;

        // Must be originator
        if !op.is_client_initiated() {
            return false;
        }
        // Capped speculative paths
        if op.speculative_paths >= MAX_SPECULATIVE_PATHS {
            return false;
        }
        let elapsed = op.id.elapsed();

        if op.ack_received {
            // ACK received — trust chain for PROGRESS_TIMEOUT, then re-enable (#3570)
            if elapsed <= PROGRESS_TIMEOUT {
                return false;
            }
            // Chain stalled past PROGRESS_TIMEOUT — eligible for retry
            let base = PROGRESS_TIMEOUT + ACK_TIMEOUT * (retry_count as u32);
            return elapsed > base;
        }

        // No ACK — check against ACK_TIMEOUT (without jitter for deterministic testing)
        let base = ACK_TIMEOUT * (retry_count as u32 + 1);
        elapsed > base
    }

    #[test]
    fn ack_received_prevents_gc_retry_within_progress_timeout() {
        use crate::config::GlobalSimulationTime;

        let base_ms = 1_700_000_000_000;
        GlobalSimulationTime::set_time_ms(base_ms);

        let mut op = make_awaiting_op(vec![make_peer(5001)], &[]);
        op.ack_received = true;

        // Advance time past ACK_TIMEOUT (3s) but within PROGRESS_TIMEOUT (7s)
        GlobalSimulationTime::set_time_ms(base_ms + 5_000);

        assert!(
            !gc_would_retry(&op, 0),
            "Op with ack_received should NOT be retried within PROGRESS_TIMEOUT"
        );
    }

    #[test]
    fn ack_received_allows_retry_after_progress_timeout() {
        use crate::config::GlobalSimulationTime;

        let base_ms = 1_700_000_000_000;
        GlobalSimulationTime::set_time_ms(base_ms);

        let mut op = make_awaiting_op(vec![make_peer(5001)], &[]);
        op.ack_received = true;

        // Advance time past PROGRESS_TIMEOUT (7s) + ACK_TIMEOUT (3s) for jitter headroom
        GlobalSimulationTime::set_time_ms(base_ms + 12_000);

        assert!(
            gc_would_retry(&op, 0),
            "Op with ack_received SHOULD be retried after PROGRESS_TIMEOUT (#3570)"
        );
    }

    #[test]
    fn speculative_paths_caps_at_max() {
        use crate::config::GlobalSimulationTime;

        let base_ms = 1_700_000_000_000;
        GlobalSimulationTime::set_time_ms(base_ms);

        let mut op = make_awaiting_op(vec![make_peer(5001), make_peer(5002)], &[]);
        op.speculative_paths = 2; // MAX_SPECULATIVE_PATHS

        GlobalSimulationTime::set_time_ms(base_ms + 10_000);

        assert!(
            !gc_would_retry(&op, 0),
            "Op at MAX_SPECULATIVE_PATHS should NOT be retried by GC"
        );
    }

    #[test]
    fn no_ack_allows_gc_retry_after_timeout() {
        use crate::config::GlobalSimulationTime;

        let base_ms = 1_700_000_000_000;
        GlobalSimulationTime::set_time_ms(base_ms);

        let op = make_awaiting_op(vec![make_peer(5001)], &[]);
        assert!(!op.ack_received);
        assert_eq!(op.speculative_paths, 0);

        // Before ACK_TIMEOUT — should NOT retry
        GlobalSimulationTime::set_time_ms(base_ms + 2_000);
        assert!(
            !gc_would_retry(&op, 0),
            "Op should NOT be retried before ACK_TIMEOUT (3s)"
        );

        // After ACK_TIMEOUT — SHOULD retry
        GlobalSimulationTime::set_time_ms(base_ms + 4_000);
        assert!(
            gc_would_retry(&op, 0),
            "Op without ACK should be retried after 3s"
        );

        // And retry should succeed since alternatives exist
        let result = op.retry_with_next_alternative(7, &[]);
        assert!(result.is_ok(), "Should retry with available alternative");
    }

    #[test]
    fn gc_retry_increments_speculative_paths_and_resets_ack() {
        use crate::config::GlobalSimulationTime;

        let base_ms = 1_700_000_000_000;
        GlobalSimulationTime::set_time_ms(base_ms);

        let op = make_awaiting_op(vec![make_peer(5001), make_peer(5002)], &[]);
        assert_eq!(op.speculative_paths, 0);
        assert!(!op.ack_received);

        // Simulate first retry (as GC task does)
        GlobalSimulationTime::set_time_ms(base_ms + 4_000);
        let (mut new_op, _msg) = op
            .retry_with_next_alternative(7, &[])
            .map_err(|_| "retry_with_next_alternative failed")
            .unwrap();
        new_op.speculative_paths += 1;
        new_op.ack_received = false;

        assert_eq!(new_op.speculative_paths, 1);
        assert!(!new_op.ack_received);

        // After ACK arrives on the new path
        new_op.ack_received = true;
        assert!(
            !gc_would_retry(&new_op, 1),
            "Op with ACK on new path should NOT be retried"
        );
    }

    // ── Intermediate node stats tracking tests (#3527) ─────────────────────

    use crate::ring::Location;

    fn make_get_op_with_stats(stats: Option<Box<GetStats>>) -> GetOp {
        GetOp {
            id: Transaction::new::<GetMsg>(),
            state: Some(GetState::ReceivedRequest),
            result: None,
            stats,
            upstream_addr: None,
            local_fallback: None,
            auto_fetch: false,
            ack_received: false,
            speculative_paths: 0,
        }
    }

    fn make_get_stats(
        target: PeerKeyLocation,
        contract_location: Location,
    ) -> Option<Box<GetStats>> {
        Some(Box::new(GetStats {
            next_peer: Some(target),
            contract_location,
            first_response_time: None,
            transfer_time: None,
        }))
    }

    /// Non-finalized GET with stats reports ContractOpFailure on timeout.
    #[test]
    fn test_get_failure_outcome_with_stats() {
        let target = make_peer(9001);
        let contract_location = Location::random();
        let op = make_get_op_with_stats(make_get_stats(target.clone(), contract_location));

        match op.outcome() {
            OpOutcome::ContractOpFailure {
                target_peer,
                contract_location: loc,
            } => {
                assert_eq!(target_peer, &target);
                assert_eq!(loc, contract_location);
            }
            other => panic!("Expected ContractOpFailure, got {other:?}"),
        }
    }

    /// Non-finalized GET without stats reports Incomplete.
    #[test]
    fn test_get_failure_outcome_without_stats() {
        let op = make_get_op_with_stats(None);
        assert!(
            matches!(op.outcome(), OpOutcome::Incomplete),
            "GET without stats should return Incomplete"
        );
    }

    /// failure_routing_info() returns correct peer and location from stats.
    #[test]
    fn test_get_failure_routing_info() {
        let target = make_peer(9002);
        let contract_location = Location::random();
        let op = make_get_op_with_stats(make_get_stats(target.clone(), contract_location));

        let (peer, loc) = op.failure_routing_info().expect("should have routing info");
        assert_eq!(peer, target);
        assert_eq!(loc, contract_location);
    }
}