freenet 0.2.94

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
//! Clients events related logic and type definitions. For example, receival of client events from applications throught the HTTP API.

// pub(crate) mod admin_endpoints; // TODO: Add axum dependencies
pub(crate) mod combinator;
pub(crate) mod error;
#[cfg(test)]
mod integration_verification;
pub(crate) mod proxy;
pub(crate) mod result_router;
pub(crate) mod session_actor;
pub(crate) mod test;
#[cfg(test)]
mod test_correlation;
pub(crate) mod types;
/// Per-user operation/export rate limiting for hosted mode (#4561, P5 of #4381).
/// Not gated on the `websocket` feature: it has no axum dependency (just
/// `DashMap` + `tokio::time` + `UserId`) and its `DEFAULT_*` constants are the
/// single source of truth for the operator-config defaults in `config.rs`,
/// which compiles with or without the feature.
pub(crate) mod user_op_rate_limit;
#[cfg(feature = "websocket")]
pub(crate) mod websocket;

pub(crate) use error::{Error, ensure_peer_ready};
pub(crate) use proxy::BoxedClient;
pub use proxy::ClientEventsProxy;
pub(crate) use types::HostIncomingMsg;
pub use types::{AuthToken, ClientId, HostResult, OpenRequest, RequestId};

use either::Either;
use freenet_stdlib::{
    client_api::{
        ClientError, ClientRequest, ContractRequest, ContractResponse, ErrorKind, HostResponse,
        QueryResponse,
    },
    prelude::*,
};
use futures::stream::FuturesUnordered;
use futures::{FutureExt, StreamExt, future::BoxFuture};
use std::convert::Infallible;
use tracing::Instrument;

use crate::contract::{ClientResponsesReceiver, ContractHandlerEvent};
use crate::message::{NodeEvent, QueryResult};
use crate::node::OpManager;
use crate::operations::{OpError, get, put, update};
use crate::ring::KnownPeerKeyLocation;
use crate::tracing::NetEventLog;
use crate::{config::GlobalExecutor, contract::StoreResponse};

use crate::contract::{contains_debug_sections, debug_sections};

/// Helper function to register a subscription listener for GET/PUT operations with auto-subscribe
async fn register_subscription_listener(
    op_manager: &OpManager,
    instance_id: ContractInstanceId,
    client_id: ClientId,
    subscription_listener: mpsc::Sender<HostResult>,
    operation_type: &str,
) -> Result<(), Error> {
    tracing::debug!(
        client_id = %client_id,
        contract = %instance_id,
        operation = operation_type,
        "Registering subscription listener"
    );
    let register_listener = op_manager
        .notify_contract_handler_prioritized(
            ContractHandlerEvent::RegisterSubscriberListener {
                key: instance_id,
                client_id,
                summary: None, // No summary for GET/PUT-based subscriptions
                subscriber_listener: subscription_listener,
            },
            crate::contract::Priority::ClientLocal,
        )
        .await
        .inspect_err(|err| {
            tracing::error!(
                client_id = %client_id,
                contract = %instance_id,
                operation = operation_type,
                error = %err,
                "Register subscriber listener failed"
            );
        });
    match register_listener {
        Ok(ContractHandlerEvent::RegisterSubscriberListenerResponse) => {
            tracing::debug!(
                client_id = %client_id,
                contract = %instance_id,
                operation = operation_type,
                "Subscriber listener registered successfully"
            );
            // Register client subscription to prevent upstream unsubscription while this client is active
            let result = op_manager
                .ring
                .add_client_subscription(&instance_id, client_id);
            // Emit telemetry if this was the first client (hosting started)
            if result.is_first_client {
                if let Some(event) = NetEventLog::hosting_started(&op_manager.ring, instance_id) {
                    op_manager.ring.register_events(Either::Left(event)).await;
                }
            }
            Ok(())
        }
        _ => {
            tracing::error!(
                client_id = %client_id,
                contract = %instance_id,
                operation = operation_type,
                phase = "registration_failed",
                "Subscriber listener registration failed"
            );
            Err(Error::Op(OpError::UnexpectedOpState))
        }
    }
}

/// Report an operation init failure to the client via the result router.
async fn report_op_init_error(
    op_manager: &OpManager,
    tx: crate::message::Transaction,
    contract: &(impl std::fmt::Display + Sync),
    op_name: &str,
    err: &OpError,
    client_id: ClientId,
    request_id: RequestId,
) {
    tracing::error!(
        client_id = %client_id,
        request_id = %request_id,
        tx = %tx,
        contract = %contract,
        error = %err,
        phase = "error",
        "{op_name} request failed"
    );

    // Convert ring errors to type-safe ErrorKind variants so that downstream
    // consumers (e.g. the HTTP handler's SERVICE_UNAVAILABLE page) can match on
    // them instead of relying on error message string contents.
    let error_kind = match err {
        OpError::RingError(crate::ring::RingError::EmptyRing) => ErrorKind::EmptyRing,
        OpError::RingError(crate::ring::RingError::PeerNotJoined) => ErrorKind::PeerNotJoined,
        // Admission-gate rejection during graceful shutdown — surface
        // as the existing `Shutdown` kind so clients see the same
        // typed reason as a mid-flight cancellation. Without an
        // explicit arm here the match is non-exhaustive (CI fails),
        // so this also serves as the source-of-truth for the
        // user-visible shape of `OpError::NodeShuttingDown`.
        OpError::NodeShuttingDown => ErrorKind::Shutdown,
        // Phase 7 egress self-block (#4300): a local client originated a
        // request for a contract this node has banned. Surface as a
        // typed `OperationError` (no dedicated wire variant exists in
        // stdlib, and adding one would be a wire-format change requiring
        // a separate stdlib-first release) so the client sees a clear,
        // contract-named reason instead of a silent timeout.
        OpError::ContractBanned { .. }
        | OpError::RingError(crate::ring::RingError::ConnError(_))
        | OpError::RingError(crate::ring::RingError::NoHostingPeers(_))
        | OpError::ConnError(_)
        | OpError::ContractError(_)
        | OpError::ExecutorError(_)
        | OpError::UnexpectedOpState
        | OpError::InvalidStateTransition { .. }
        | OpError::NotificationError
        | OpError::PeerDisconnected { .. }
        | OpError::NotificationChannelError(_)
        | OpError::IncorrectTxType(..)
        | OpError::OpNotPresent(_)
        | OpError::StreamCancelled
        | OpError::OrphanStreamClaimFailed => ErrorKind::OperationError {
            cause: format!("{op_name} operation failed: {err}").into(),
        },
    };

    let error_response = Err(error_kind.into());

    if let Err(e) = op_manager.result_router_tx.try_send((tx, error_response)) {
        tracing::error!(
            tx = %tx,
            error = %e,
            "Failed to send {op_name} error to result router \
             (channel full or closed)"
        );
    }

    // Clean up request router so subsequent requests for the same resource
    // create a fresh operation instead of reusing this failed transaction.
    // Without this, the resource→transaction mapping persists and new clients
    // get stale cached errors indefinitely (see diagnostic report 8TSMXY).
    op_manager.completed(tx);
}

/// Process client events.
///
/// # Architecture: Dual-Mode Client Handling
///
/// This function operates in one of two modes based on `op_manager.actor_clients`:
///
/// - Uses ResultRouter → SessionActor for centralized client communication
/// - Uses RequestRouter for operation deduplication (multiple clients share one operation)
/// - More scalable and efficient for concurrent clients
pub async fn client_event_handling<ClientEv>(
    op_manager: Arc<OpManager>,
    mut client_events: ClientEv,
    mut client_responses: ClientResponsesReceiver,
    node_controller: tokio::sync::mpsc::Sender<NodeEvent>,
) -> anyhow::Result<Infallible>
where
    ClientEv: ClientEventsProxy + Send + 'static,
{
    let request_router = std::sync::Arc::new(crate::node::RequestRouter::new());
    // Register the router with op_manager so completed operations clean up stale entries.
    // Without this, subsequent requests for the same resource would hang forever.
    op_manager.set_request_router(request_router.clone());
    let request_router = Some(request_router);
    let mut results = FuturesUnordered::new();
    loop {
        // Uses deterministic_select! for DST - guards are evaluated BEFORE futures are created
        crate::deterministic_select! {
            client_request = client_events.recv() => {
                let req = match client_request {
                    Ok(request) => {
                        tracing::debug!(
                            client_id = %request.client_id,
                            request_id = %request.request_id,
                            request_type = ?request.request,
                            "Received client request"
                        );
                        request
                    }
                    Err(error) if matches!(error.kind(), ErrorKind::Shutdown) => {
                        node_controller.send(NodeEvent::Disconnect { cause: None }).await.ok();
                        anyhow::bail!("shutdown event");
                    }
                    Err(error) if matches!(error.kind(), ErrorKind::TransportProtocolDisconnect) => {
                        // A single client disconnecting is not fatal — continue serving
                        // other clients. The combinator already cleaned up the dead slot.
                        tracing::debug!(error = %error, "Client transport disconnected");
                        continue;
                    }
                    Err(error) => {
                        tracing::debug!(error = %error, "Client error");
                        continue;
                    }
                };
                let cli_id = req.client_id;
                let res = process_open_request(req, op_manager.clone(), request_router.clone()).await;
                results.push(async move {
                    match res.await {
                        Ok(Some(Either::Left(res))) => (cli_id, Ok(Some(res))),
                        Ok(Some(Either::Right(mut cb))) => {
                            match cb.recv().await {
                                Some(res) => (cli_id, Ok(Some(res))),
                                None => (cli_id, Err(ClientError::from(ErrorKind::ChannelClosed))),
                            }
                        }
                        Ok(None) => (cli_id, Ok(None)),
                        Err(Error::Disconnected) => {
                            tracing::debug!(client_id = %cli_id, "Client disconnected");
                            (cli_id, Err(ClientError::from(ErrorKind::Disconnect)))
                        }
                        Err(Error::PeerNotJoined) => {
                            tracing::warn!(
                                client_id = %cli_id,
                                "Operation rejected: peer has not joined network yet - client should retry after join"
                            );
                            (cli_id, Err(ErrorKind::PeerNotJoined.into()))
                        }
                        Err(Error::EmptyRing) => {
                            tracing::warn!(
                                client_id = %cli_id,
                                "Operation rejected: no ring connections found - client should retry after connections are established"
                            );
                            (cli_id, Err(ErrorKind::EmptyRing.into()))
                        }
                        Err(err) => {
                            tracing::error!(
                                client_id = %cli_id,
                                error = %err,
                                "Operation error"
                            );
                            (cli_id, Err(ErrorKind::OperationError { cause: format!("{err}").into() }.into()))
                        }
                    }
                });
            },
            res = client_responses.recv() => {
                if let Some((cli_id, request_id, res)) = res {
                    if let Ok(result) = &res {
                        tracing::debug!(
                            client_id = %cli_id,
                            request_id = %request_id,
                            response = %result,
                            "Sending client response"
                        );
                    }
                    if let Err(err) = client_events.send(cli_id, res).await {
                        tracing::debug!(
                            client_id = %cli_id,
                            error = %err,
                            "Client channel closed, response dropped"
                        );
                    }
                }
            },
            res = results.next(), if !results.is_empty() => {
                let Some(f_res) = res else {
                    unreachable!("results.next() should only return None if results is empty, which is guarded against");
                };
                match f_res {
                    (cli_id, Ok(Some(res))) => {
                        let res = match res {
                            QueryResult::Connections(conns) => {
                                // Connected peers must have known addresses - use type-safe conversion
                                Ok(HostResponse::QueryResponse(QueryResponse::ConnectedPeers {
                                    peers: conns.into_iter().filter_map(|p| {
                                        KnownPeerKeyLocation::try_from(&p).ok().map(|known| {
                                            (p.pub_key.to_string(), known.socket_addr())
                                        })
                                    }).collect() }
                                ))
                            }
                            QueryResult::GetResult { key, state, contract } => {
                                Ok(HostResponse::ContractResponse(ContractResponse::GetResponse {
                                    key,
                                    state,
                                    contract,
                                }))
                            }
                            QueryResult::DelegateResult { response, .. } => {
                                response
                            }
                            QueryResult::NetworkDebug(debug_info) => {
                                // Convert internal types to stdlib types
                                let subscriptions = debug_info.application_subscriptions.into_iter().map(|sub| {
                                    freenet_stdlib::client_api::SubscriptionInfo {
                                        contract_key: sub.instance_id,
                                        client_id: sub.client_id.into(),
                                    }
                                }).collect();

                                // Connected peers must have known addresses - use type-safe conversion
                                let connected_peers = debug_info.connected_peers.into_iter().filter_map(|peer| {
                                    KnownPeerKeyLocation::try_from(&peer).ok().map(|known| {
                                        (peer.to_string(), known.socket_addr())
                                    })
                                }).collect();

                                Ok(HostResponse::QueryResponse(QueryResponse::NetworkDebug(
                                    freenet_stdlib::client_api::NetworkDebugInfo {
                                        subscriptions,
                                        connected_peers,
                                    }
                                )))
                            }
                            QueryResult::NodeDiagnostics(response) => {
                                Ok(HostResponse::QueryResponse(QueryResponse::NodeDiagnostics(response)))
                            }
                        };
                        if let Ok(result) = &res {
                            tracing::debug!(
                                client_id = %cli_id,
                                response = %result,
                                "Sending client operation response"
                            );
                        }
                        if let Err(err) = client_events.send(cli_id, res).await {
                            tracing::debug!(
                                client_id = %cli_id,
                                error = %err,
                                "Client channel closed, operation response dropped"
                            );
                        }
                    }
                    (_, Ok(None)) => continue,
                    (cli_id, Err(err)) => {
                        tracing::error!(
                            client_id = %cli_id,
                            error = %err,
                            "Sending error response to client"
                        );
                        if let Err(send_err) = client_events.send(cli_id, Err(err)).await {
                            tracing::debug!(
                                client_id = %cli_id,
                                error = %send_err,
                                "Client channel closed, error response dropped"
                            );
                        }
                    }
                }
            },
        }
    }
}

#[inline]
async fn process_open_request(
    mut request: OpenRequest<'static>,
    op_manager: Arc<OpManager>,
    request_router: Option<Arc<crate::node::RequestRouter>>,
) -> BoxFuture<'static, Result<Option<Either<QueryResult, mpsc::Receiver<QueryResult>>>, Error>> {
    let (callback_tx, callback_rx) = if matches!(
        &*request.request,
        ClientRequest::NodeQueries(_) | ClientRequest::ContractOp(ContractRequest::Get { .. })
    ) {
        let (tx, rx) = mpsc::channel(1);
        (Some(tx), Some(rx))
    } else {
        (None, None)
    };

    // TODO: wait until we have a peer_id to attempt (should be connected)
    // this will indirectly start actions on the local contract executor
    let fut = async move {
        let client_id = request.client_id;
        let request_id = request.request_id;

        let subscription_listener: Option<mpsc::Sender<HostResult>> =
            request.notification_channel.take();

        match *request.request {
            ClientRequest::ContractOp(ops) => {
                match ops {
                    ContractRequest::Put {
                        state,
                        contract,
                        related_contracts,
                        subscribe,
                        blocking_subscribe,
                    } => {
                        let peer_id = ensure_peer_ready(&op_manager)?;

                        tracing::debug!(
                            client_id = %client_id,
                            request_id = %request_id,
                            peer = %peer_id,
                            phase = "request",
                            "Received PUT request from client"
                        );

                        let contract_key = contract.key();

                        // Driver handles both local-only and network
                        // PUTs: calls put_contract locally, finds
                        // peers, sends the request. Each task owns
                        // its own operation lifecycle.
                        let client_tx = crate::message::Transaction::new::<put::PutMsg>();

                        op_manager
                            .ch_outbound
                            .waiting_for_transaction_result(client_tx, client_id, request_id)
                            .await
                            .inspect_err(|err| {
                                tracing::error!(
                                    client_id = %client_id,
                                    request_id = %request_id,
                                    tx = %client_tx,
                                    error = %err,
                                    "Error waiting for transaction result"
                                )
                            })?;

                        // Reject debug-compiled contracts BEFORE routing
                        // (#2257). Debug WASM carries DWARF `.debug_*`
                        // custom sections and is typically 10-100x larger
                        // than release builds, which can blow past
                        // WebSocket message-size limits and surface as a
                        // confusing "Message too long" transport error.
                        // Failing here gives the client an actionable
                        // "recompile with --release" message instead.
                        if contains_debug_sections(contract.data()) {
                            // Re-scan only on the (rare) rejection path to
                            // name the offending sections in the error.
                            let detected = debug_sections(contract.data());
                            let err = OpError::ContractError(
                                crate::contract::ContractError::DebugWasmRejected {
                                    sections: detected.join(", "),
                                },
                            );
                            report_op_init_error(
                                &op_manager,
                                client_tx,
                                &contract_key,
                                "PUT",
                                &err,
                                client_id,
                                request_id,
                            )
                            .await;
                            return Ok(None);
                        }

                        if subscribe {
                            if let Some(sl) = subscription_listener {
                                register_subscription_listener(
                                    &op_manager,
                                    *contract_key.id(),
                                    client_id,
                                    sl,
                                    "PUT",
                                )
                                .await?;
                            } else {
                                tracing::warn!(
                                    client_id = %client_id,
                                    contract = %contract_key,
                                    "PUT with subscribe=true but no subscription_listener"
                                );
                            }
                        }

                        if let Err(err) = put::op_ctx_task::start_client_put(
                            op_manager.clone(),
                            client_tx,
                            contract,
                            related_contracts,
                            state,
                            op_manager.ring.max_hops_to_live,
                            subscribe,
                            blocking_subscribe,
                        )
                        .await
                        {
                            report_op_init_error(
                                &op_manager,
                                client_tx,
                                &contract_key,
                                "PUT",
                                &err,
                                client_id,
                                request_id,
                            )
                            .await;
                        }
                    }
                    ContractRequest::Update { key, data } => {
                        let peer_id = ensure_peer_ready(&op_manager)?;

                        tracing::debug!(
                            client_id = %client_id,
                            request_id = %request_id,
                            peer = %peer_id,
                            contract = %key,
                            phase = "request",
                            "Received UPDATE request from client"
                        );

                        let related_contracts = RelatedContracts::default();

                        tracing::debug!(
                            client_id = %client_id,
                            request_id = %request_id,
                            peer = %peer_id,
                            contract = %key,
                            data = ?data,
                            phase = "starting",
                            "Starting UPDATE operation - passing delta to network layer"
                        );

                        // Convert UpdateData to 'static lifetime for storage in operation state.
                        // This is safe because we're cloning the underlying bytes.
                        let update_data: UpdateData<'static> = match data {
                            UpdateData::State(s) => UpdateData::State(State::from(s.into_bytes())),
                            UpdateData::Delta(d) => {
                                UpdateData::Delta(StateDelta::from(d.into_bytes()))
                            }
                            UpdateData::StateAndDelta { state, delta } => {
                                UpdateData::StateAndDelta {
                                    state: State::from(state.into_bytes()),
                                    delta: StateDelta::from(delta.into_bytes()),
                                }
                            }
                            UpdateData::RelatedState { related_to, state } => {
                                UpdateData::RelatedState {
                                    related_to,
                                    state: State::from(state.into_bytes()),
                                }
                            }
                            UpdateData::RelatedDelta { related_to, delta } => {
                                UpdateData::RelatedDelta {
                                    related_to,
                                    delta: StateDelta::from(delta.into_bytes()),
                                }
                            }
                            UpdateData::RelatedStateAndDelta {
                                related_to,
                                state,
                                delta,
                            } => UpdateData::RelatedStateAndDelta {
                                related_to,
                                state: State::from(state.into_bytes()),
                                delta: StateDelta::from(delta.into_bytes()),
                            },
                            // `UpdateData` is `#[non_exhaustive]` since
                            // stdlib 0.6.0. Future variants reach this
                            // arm because the compiler requires it; until
                            // they are explicitly handled (each variant
                            // has its own owned-bytes conversion), reject
                            // them here rather than silently dropping the
                            // payload further down the operation pipeline.
                            other => {
                                tracing::error!(
                                    client_id = %client_id,
                                    request_id = %request_id,
                                    contract = %key,
                                    variant = ?std::mem::discriminant(&other),
                                    "Rejecting UPDATE: unknown UpdateData variant — \
                                     freenet-core was built against an older stdlib than \
                                     the client expected; rebuild the host to handle this variant"
                                );
                                return Err(Error::Node(
                                    "UPDATE rejected: unknown UpdateData variant from client; \
                                     rebuild freenet-core against the stdlib version emitting \
                                     this variant"
                                        .to_string(),
                                ));
                            }
                        };

                        tracing::debug!(
                            client_id = %client_id,
                            request_id = %request_id,
                            peer = %peer_id,
                            contract = %key,
                            phase = "sending",
                            "Sending UPDATE operation to network layer"
                        );

                        if let Some(router) = &request_router {
                            tracing::debug!(
                                client_id = %client_id,
                                request_id = %request_id,
                                peer = %peer_id,
                                contract = %key,
                                phase = "routing",
                                "Routing UPDATE request through deduplication layer"
                            );

                            let request = crate::node::DeduplicatedRequest::Update {
                                key,
                                update_data: update_data.clone(),
                                related_contracts: related_contracts.clone(),
                                client_id,
                                request_id,
                            };

                            let (transaction_id, should_start_operation) =
                                router.route_request(request).await.map_err(|e| {
                                    Error::Node(format!("Request routing failed: {}", e))
                                })?;

                            // Always register this client for the result
                            op_manager
                                .ch_outbound
                                .waiting_for_transaction_result(
                                    transaction_id,
                                    client_id,
                                    request_id,
                                )
                                .await
                                .inspect_err(|err| {
                                    tracing::error!(
                                        "Error waiting for transaction result: {}",
                                        err
                                    );
                                })?;

                            // Only start new network operation if this is a new operation
                            if should_start_operation {
                                tracing::debug!(
                                    client_id = %client_id,
                                    request_id = %request_id,
                                    tx = %transaction_id,
                                    peer = %peer_id,
                                    contract = %key,
                                    phase = "new_operation",
                                    "Starting new UPDATE network operation"
                                );

                                tracing::debug!(
                                    request_id = %request_id,
                                    transaction_id = %transaction_id,
                                    operation = "update",
                                    "Request-Transaction correlation"
                                );

                                match update::op_ctx_task::start_client_update(
                                    op_manager.clone(),
                                    transaction_id,
                                    key,
                                    update_data.clone(),
                                    related_contracts,
                                )
                                .await
                                {
                                    Ok(_) => {}
                                    Err(err) => {
                                        report_op_init_error(
                                            &op_manager,
                                            transaction_id,
                                            &key,
                                            "UPDATE",
                                            &err,
                                            client_id,
                                            request_id,
                                        )
                                        .await;
                                    }
                                }
                            } else {
                                tracing::debug!(
                                    client_id = %client_id,
                                    request_id = %request_id,
                                    tx = %transaction_id,
                                    peer = %peer_id,
                                    contract = %key,
                                    phase = "reuse",
                                    "Reusing existing UPDATE operation - client registered for result"
                                );
                            }
                        } else {
                            tracing::debug!(
                                client_id = %client_id,
                                request_id = %request_id,
                                peer = %peer_id,
                                contract = %key,
                                phase = "legacy",
                                "Starting direct UPDATE operation (legacy mode)"
                            );

                            // Legacy mode: direct operation without deduplication
                            let op_id = crate::message::Transaction::new::<update::UpdateMsg>();

                            tracing::debug!(
                                request_id = %request_id,
                                transaction_id = %op_id,
                                operation = "update",
                                "Request-Transaction correlation"
                            );

                            op_manager
                                .ch_outbound
                                .waiting_for_transaction_result(op_id, client_id, request_id)
                                .await
                                .inspect_err(|err| {
                                    tracing::error!(
                                        "Error waiting for transaction result: {}",
                                        err
                                    );
                                })?;

                            if let Err(err) = update::op_ctx_task::start_client_update(
                                op_manager.clone(),
                                op_id,
                                key,
                                update_data,
                                related_contracts,
                            )
                            .await
                            {
                                report_op_init_error(
                                    &op_manager,
                                    op_id,
                                    &key,
                                    "UPDATE",
                                    &err,
                                    client_id,
                                    request_id,
                                )
                                .await;
                            }
                        }
                    }
                    ContractRequest::Get {
                        key,
                        return_contract_code,
                        subscribe,
                        blocking_subscribe,
                    } => {
                        // Try local cache before requiring ring join for non-subscribe GETs.
                        let peer_id = match ensure_peer_ready(&op_manager) {
                            Ok(id) => id,
                            Err(err) if !subscribe => {
                                // Not joined yet — check if we can serve from local cache
                                let local_result = op_manager
                                    .notify_contract_handler_prioritized(
                                        ContractHandlerEvent::GetQuery {
                                            instance_id: key,
                                            return_contract_code,
                                        },
                                        crate::contract::Priority::ClientLocal,
                                    )
                                    .await;
                                if let Ok(ContractHandlerEvent::GetResponse {
                                    key: Some(full_key),
                                    response:
                                        Ok(StoreResponse {
                                            state: Some(state),
                                            contract,
                                        }),
                                }) = local_result
                                {
                                    if !return_contract_code || contract.is_some() {
                                        tracing::info!(
                                            client_id = %client_id,
                                            contract = %full_key,
                                            phase = "local_cache_pre_join",
                                            "Serving locally cached contract state before network join"
                                        );
                                        return Ok(Some(Either::Left(QueryResult::GetResult {
                                            key: full_key,
                                            state,
                                            contract,
                                        })));
                                    }
                                }
                                // No local cache — propagate the original error
                                return Err(err);
                            }
                            Err(err) => return Err(err),
                        };

                        // Query local store first. We use the result in two cases:
                        // 1. Error handling: if local storage has issues, fail fast
                        // 2. No connections: if isolated (no peers), return local cache immediately
                        //
                        // For connected nodes, we use smart cache routing: return local cache
                        // if subscribed (cache is fresh), otherwise fetch from network.
                        // See PR #2388 for why always-local-first was problematic.
                        let (full_key, state, contract) = match op_manager
                            .notify_contract_handler_prioritized(
                                ContractHandlerEvent::GetQuery {
                                    instance_id: key,
                                    return_contract_code,
                                },
                                crate::contract::Priority::ClientLocal,
                            )
                            .await
                        {
                            Ok(ContractHandlerEvent::GetResponse {
                                key: Some(full_key),
                                response: Ok(StoreResponse { state, contract }),
                            }) => (Some(full_key), state, contract),
                            Ok(ContractHandlerEvent::GetResponse {
                                key: None,
                                response:
                                    Ok(StoreResponse {
                                        state: None,
                                        contract: None,
                                    }),
                            }) => (None, None, None), // Contract not found locally
                            Ok(ContractHandlerEvent::GetResponse {
                                response: Err(err), ..
                            }) => {
                                tracing::error!(
                                    client_id = %client_id,
                                    request_id = %request_id,
                                    %key,
                                    error = %err,
                                    phase = "error",
                                    "GET query failed (executor error)"
                                );
                                return Err(Error::Executor(err));
                            }
                            Err(err) => {
                                tracing::error!(
                                    client_id = %client_id,
                                    request_id = %request_id,
                                    %key,
                                    error = %err,
                                    phase = "error",
                                    "GET query failed (contract error)"
                                );
                                return Err(Error::Contract(err));
                            }
                            Ok(_) => {
                                tracing::error!(
                                    client_id = %client_id,
                                    request_id = %request_id,
                                    %key,
                                    phase = "error",
                                    "GET query failed (unexpected state)"
                                );
                                return Err(Error::Op(OpError::UnexpectedOpState));
                            }
                        };

                        // Determine whether to route through network or return local cache.
                        //
                        // If we're actively receiving updates (is_receiving_updates), our
                        // local cache is fresh and we can return it directly. Otherwise,
                        // fetch from network to avoid serving stale state.
                        // See PR #2388 (original fix) and #3340 (LRU staleness fix).
                        let connection_count = op_manager.ring.open_connections();
                        let has_local_state = full_key.is_some() && state.is_some();
                        let local_satisfies_request =
                            has_local_state && (!return_contract_code || contract.is_some());

                        // Only return local cache if we're actively receiving updates
                        // (network subscription or client subscriptions). The hosting
                        // LRU cache alone is insufficient — contracts can outlive their
                        // subscriptions, leaving stale state (see #3340).
                        let is_subscribed = full_key
                            .as_ref()
                            .map(|k| op_manager.ring.is_receiving_updates(k))
                            .unwrap_or(false);

                        // Mark as locally accessed (#3769) and refresh hosting TTL.
                        if let Some(ref fk) = full_key {
                            op_manager.ring.mark_local_client_access(fk);
                            if op_manager.ring.is_hosting_contract(fk) {
                                op_manager.ring.touch_hosting(fk);
                            }
                        }

                        // Serve from local cache only if the local user requested
                        // this contract (not just relay-cached).
                        let is_locally_hosted = full_key
                            .as_ref()
                            .map(|k| {
                                op_manager.ring.is_hosting_contract(k)
                                    && op_manager.ring.has_local_client_access(k)
                            })
                            .unwrap_or(false);

                        // Return local cache if we have valid state AND any of:
                        // 1. No connections (isolated node)
                        // 2. Actively subscribed (cache kept fresh via updates)
                        // 3. Locally hosted (subscription may be in progress)
                        if local_satisfies_request
                            && (connection_count == 0 || is_subscribed || is_locally_hosted)
                        {
                            let full_key = full_key.unwrap();
                            let state = state.unwrap();

                            tracing::info!(
                                client_id = %client_id,
                                request_id = %request_id,
                                peer = %peer_id,
                                contract = %full_key,
                                is_subscribed,
                                is_locally_hosted,
                                connection_count,
                                phase = "local_cache",
                                "Returning locally cached contract state"
                            );

                            // #4642 A3 hit-rate instrumentation: this client GET
                            // was answered from local hosted state (a hit).
                            op_manager.ring.record_get_served_locally();

                            // Handle subscription for locally found contracts
                            if subscribe {
                                if let Some(subscription_listener) = subscription_listener {
                                    register_subscription_listener(
                                        &op_manager,
                                        *full_key.id(),
                                        client_id,
                                        subscription_listener,
                                        "local GET",
                                    )
                                    .await?;
                                } else {
                                    // Expected for HTTP web endpoint which sets subscribe=true
                                    // but has no notification channel. The subscription is
                                    // handled at the node level, not the client level.
                                    tracing::debug!(
                                        client_id = %client_id,
                                        contract = %full_key,
                                        "GET with subscribe=true but no subscription_listener (expected for HTTP clients)"
                                    );
                                }
                            }

                            return Ok(Some(Either::Left(QueryResult::GetResult {
                                key: full_key,
                                state,
                                contract,
                            })));
                        }

                        // #4642 A3 hit-rate instrumentation: this client GET could
                        // not be answered locally and is routed to the network
                        // (a forward/miss).
                        op_manager.ring.record_get_forwarded();

                        // Driver owns its routing state in task
                        // locals and calls notify_contract_handler
                        // locally as needed.
                        tracing::debug!(
                            client_id = %client_id,
                            request_id = %request_id,
                            peer = %peer_id,
                            contract = %key,
                            has_local = has_local_state,
                            is_subscribed,
                            connection_count,
                            phase = "network_routing",
                            "Routing GET request through network"
                        );

                        let client_tx = crate::message::Transaction::new::<get::GetMsg>();

                        op_manager
                            .ch_outbound
                            .waiting_for_transaction_result(client_tx, client_id, request_id)
                            .await
                            .inspect_err(|err| {
                                tracing::error!(
                                    client_id = %client_id,
                                    request_id = %request_id,
                                    tx = %client_tx,
                                    error = %err,
                                    "Error waiting for transaction result"
                                )
                            })?;

                        if subscribe {
                            if let Some(sl) = subscription_listener {
                                register_subscription_listener(
                                    &op_manager,
                                    key,
                                    client_id,
                                    sl,
                                    "GET",
                                )
                                .await?;
                            } else {
                                tracing::warn!(
                                    client_id = %client_id,
                                    contract = %key,
                                    "GET with subscribe=true but no subscription_listener"
                                );
                            }
                        }

                        // `report_op_init_error` takes a &ContractKey, so we
                        // synthesize one from the instance_id for the error
                        // path (the full key isn't known until a Response).
                        let key_for_err = full_key.unwrap_or_else(|| {
                            ContractKey::from_id_and_code(
                                key,
                                freenet_stdlib::prelude::CodeHash::new([0u8; 32]),
                            )
                        });
                        if let Err(err) = get::op_ctx_task::start_client_get(
                            op_manager.clone(),
                            client_tx,
                            key,
                            return_contract_code,
                            subscribe,
                            blocking_subscribe,
                        )
                        .await
                        {
                            report_op_init_error(
                                &op_manager,
                                client_tx,
                                &key_for_err,
                                "GET",
                                &err,
                                client_id,
                                request_id,
                            )
                            .await;
                        }
                    }
                    ContractRequest::Subscribe { key, summary } => {
                        let peer_id = ensure_peer_ready(&op_manager)?;

                        tracing::debug!(
                            client_id = %client_id,
                            request_id = %request_id,
                            peer = %peer_id,
                            contract = %key,
                            phase = "request",
                            "Received SUBSCRIBE request from client"
                        );

                        // Reject Subscribe if the contract WASM isn't cached locally.
                        // Without WASM, the node can't validate or apply updates,
                        // leading to a "subscribed but can't update" state.
                        // Clients must PUT or GET first (any GET will cache WASM
                        // internally regardless of return_contract_code, see #3757).
                        //
                        // Note: This only guards explicit ContractRequest::Subscribe.
                        // GET+subscribe=true and PUT+subscribe=true bypass this check
                        // because those operations inherently fetch/provide the WASM.
                        match op_manager
                            .notify_contract_handler_prioritized(
                                crate::contract::ContractHandlerEvent::GetQuery {
                                    instance_id: key,
                                    return_contract_code: true,
                                },
                                crate::contract::Priority::ClientLocal,
                            )
                            .await
                        {
                            Ok(crate::contract::ContractHandlerEvent::GetResponse {
                                response:
                                    Ok(crate::contract::StoreResponse {
                                        state: Some(_),
                                        contract: Some(_),
                                    }),
                                ..
                            }) => {
                                // Contract WASM and state are cached locally, proceed
                            }
                            Ok(crate::contract::ContractHandlerEvent::GetResponse { .. }) => {
                                tracing::warn!(
                                    client_id = %client_id,
                                    request_id = %request_id,
                                    contract = %key,
                                    "Rejecting SUBSCRIBE: contract WASM not cached locally. \
                                     PUT the contract or GET the contract first."
                                );
                                return Err(Error::Node(format!(
                                    "Cannot subscribe to contract {key}: contract WASM/parameters \
                                     not cached locally. PUT the contract or GET the contract \
                                     before subscribing."
                                )));
                            }
                            Err(err) => {
                                tracing::error!(
                                    client_id = %client_id,
                                    request_id = %request_id,
                                    contract = %key,
                                    error = %err,
                                    "Contract handler error while checking WASM for SUBSCRIBE"
                                );
                                return Err(Error::Node(format!(
                                    "Cannot subscribe to contract {key}: \
                                     failed to query contract store: {err}"
                                )));
                            }
                            Ok(unexpected) => {
                                tracing::error!(
                                    client_id = %client_id,
                                    request_id = %request_id,
                                    contract = %key,
                                    "Unexpected contract handler response for SUBSCRIBE WASM check: {unexpected:?}"
                                );
                                return Err(Error::Node(format!(
                                    "Cannot subscribe to contract {key}: \
                                     unexpected contract handler response"
                                )));
                            }
                        }

                        let Some(subscriber_listener) = subscription_listener else {
                            tracing::error!(
                                client_id = %client_id,
                                request_id = %request_id,
                                contract = %key,
                                "No subscriber listener for SUBSCRIBE request"
                            );
                            return Ok(None);
                        };

                        let register_listener = op_manager
                            .notify_contract_handler_prioritized(
                                ContractHandlerEvent::RegisterSubscriberListener {
                                    key,
                                    client_id,
                                    summary,
                                    subscriber_listener,
                                },
                                crate::contract::Priority::ClientLocal,
                            )
                            .await
                            .inspect_err(|err| {
                                tracing::error!(
                                    client_id = %client_id,
                                    request_id = %request_id,
                                    contract = %key,
                                    error = %err,
                                    "Register subscriber listener error"
                                );
                            });
                        match register_listener {
                            Ok(ContractHandlerEvent::RegisterSubscriberListenerResponse) => {
                                tracing::debug!(
                                    client_id = %client_id,
                                    request_id = %request_id,
                                    contract = %key,
                                    phase = "listener_registered",
                                    "Subscriber listener registered successfully"
                                );
                                // Register client subscription to enable subscription tree pruning on disconnect
                                let result =
                                    op_manager.ring.add_client_subscription(&key, client_id);
                                // Emit telemetry if this was the first client (hosting started)
                                if result.is_first_client {
                                    if let Some(event) =
                                        NetEventLog::hosting_started(&op_manager.ring, key)
                                    {
                                        op_manager.ring.register_events(Either::Left(event)).await;
                                    }
                                }
                            }
                            _ => {
                                tracing::error!(
                                    client_id = %client_id,
                                    request_id = %request_id,
                                    contract = %key,
                                    phase = "registration_failed",
                                    "Subscriber listener registration failed"
                                );
                                return Err(Error::Op(OpError::UnexpectedOpState));
                            }
                        }

                        // Now start the network subscription operation
                        // SUBSCRIBE: Skip router deduplication due to instant-completion race conditions
                        // When contracts are local, Subscribe completes instantly which breaks deduplication:
                        // - Client 1 subscribes → operation completes → result delivered → TX removed
                        // - Client 2 subscribes → tries to reuse TX → but TX already gone
                        // Solution: Each client gets their own Subscribe operation (they're lightweight)
                        if let Some(_router) = &request_router {
                            tracing::debug!(
                                client_id = %client_id,
                                request_id = %request_id,
                                peer = %peer_id,
                                contract = %key,
                                phase = "no_dedup",
                                "Processing SUBSCRIBE without deduplication (instant-completion race avoidance)"
                            );

                            // Create operation with new transaction ID
                            let tx = crate::message::Transaction::new::<
                                crate::operations::subscribe::SubscribeMsg,
                            >();

                            // CRITICAL: Register BEFORE starting operation to avoid race with instant-completion
                            use crate::contract::WaitingTransaction;
                            op_manager
                                .ch_outbound
                                .waiting_for_transaction_result(
                                    WaitingTransaction::Transaction(tx),
                                    client_id,
                                    request_id,
                                )
                                .await
                                .inspect_err(|err| {
                                    tracing::error!(
                                        "Error waiting for transaction result: {}",
                                        err
                                    );
                                })?;

                            // Start dedicated operation for this
                            // client AFTER registration.
                            // `subscribe_with_id` is
                            // client-initiated-only; no `is_renewal`.
                            let _result_tx = crate::node::subscribe_with_id(
                                op_manager.clone(),
                                key,
                                None, // No legacy registration
                                Some(tx),
                            )
                            .await
                            .inspect_err(|err| {
                                tracing::error!(
                                    client_id = %client_id,
                                    request_id = %request_id,
                                    tx = %tx,
                                    contract = %key,
                                    error = %err,
                                    phase = "error",
                                    "SUBSCRIBE operation failed"
                                );
                            })?;

                            tracing::debug!(
                                request_id = %request_id,
                                transaction_id = %tx,
                                operation = "subscribe",
                                "SUBSCRIBE operation started with dedicated transaction for this client"
                            );
                        } else {
                            tracing::debug!(
                                peer_id = %peer_id,
                                key = %key,
                                "Starting direct SUBSCRIBE operation",
                            );

                            // Generate transaction, register first, then run op
                            let tx = crate::message::Transaction::new::<
                                crate::operations::subscribe::SubscribeMsg,
                            >();

                            op_manager
                                .ch_outbound
                                .waiting_for_transaction_result(tx, client_id, request_id)
                                .await
                                .inspect_err(|err| {
                                    tracing::error!(
                                        "Error waiting for transaction result: {}",
                                        err
                                    );
                                })?;

                            // `subscribe_with_id` is client-initiated-only; no `is_renewal` parameter.
                            crate::node::subscribe_with_id(op_manager.clone(), key, None, Some(tx))
                                .await
                                .inspect_err(|err| {
                                    tracing::error!(
                                        client_id = %client_id,
                                        request_id = %request_id,
                                        tx = %tx,
                                        contract = %key,
                                        error = %err,
                                        phase = "error",
                                        "SUBSCRIBE operation failed"
                                    );
                                })?;

                            tracing::debug!(
                                request_id = %request_id,
                                transaction_id = %tx,
                                operation = "subscribe",
                                "Request-Transaction correlation"
                            );
                        }
                    }
                    _ => {
                        tracing::error!(
                            client_id = %client_id,
                            request_id = %request_id,
                            "Unsupported contract operation"
                        );
                    }
                }
            }
            ClientRequest::DelegateOp(req) => {
                tracing::debug!(
                    client_id = %client_id,
                    request_id = %request_id,
                    phase = "request",
                    "Received delegate operation from client"
                );
                let delegate_key = req.key().clone();

                // Register (or refresh) this app's routing path so the delegate
                // can push notification-driven ApplicationMessages back to it
                // (#3275). An app "registers with a delegate" by talking to it
                // over a connection that carries an async notification channel;
                // any ApplicationMessages request with such a channel establishes
                // the path. UnregisterDelegate tears it down. RegisterDelegate
                // (installing the delegate binary) does NOT register an app —
                // it's an admin op, not an app conversation.
                match &req {
                    freenet_stdlib::client_api::DelegateRequest::ApplicationMessages { .. } => {
                        if let Some(sender) = &subscription_listener {
                            if !crate::contract::delegate_app_registry::register_app(
                                &delegate_key,
                                client_id,
                                sender.clone(),
                            ) {
                                tracing::warn!(
                                    %client_id,
                                    delegate = %delegate_key,
                                    "App not registered for delegate notifications (registry at capacity)"
                                );
                            }
                        }
                    }
                    freenet_stdlib::client_api::DelegateRequest::UnregisterDelegate(key) => {
                        crate::contract::delegate_app_registry::remove_delegate(key);
                    }
                    // RegisterDelegate installs a delegate binary (admin op), not
                    // an app conversation, so it registers no routing path. The
                    // wildcard also absorbs future `#[non_exhaustive]` variants;
                    // it exists ONLY to satisfy non_exhaustive (see
                    // git-workflow.md) — new app-facing variants must be handled
                    // explicitly above, not swept here.
                    #[allow(clippy::wildcard_enum_match_arm)]
                    freenet_stdlib::client_api::DelegateRequest::RegisterDelegate { .. } | _ => {}
                }

                // Derive a short discriminant tag for the INFO logs, but only when INFO is
                // enabled — the Vec<&str> collect + format! would otherwise allocate on every
                // delegate dispatch even when the log line is suppressed.
                let msg_type: Option<String> = if tracing::enabled!(tracing::Level::INFO) {
                    Some(match &req {
                        freenet_stdlib::client_api::DelegateRequest::ApplicationMessages {
                            inbound,
                            ..
                        } => {
                            // Include the count of inbound message variants for observability.
                            // Each variant name is a short discriminant so operators can tell
                            // ApplicationMessage (from app) apart from GetContractResponse etc.
                            let tags: Vec<&str> = inbound
                                .iter()
                                .map(|m| match m {
                                    InboundDelegateMsg::ApplicationMessage(_) => {
                                        "ApplicationMessage"
                                    }
                                    InboundDelegateMsg::UserResponse(_) => "UserResponse",
                                    InboundDelegateMsg::GetContractResponse(_) => {
                                        "GetContractResponse"
                                    }
                                    InboundDelegateMsg::PutContractResponse(_) => {
                                        "PutContractResponse"
                                    }
                                    InboundDelegateMsg::UpdateContractResponse(_) => {
                                        "UpdateContractResponse"
                                    }
                                    InboundDelegateMsg::SubscribeContractResponse(_) => {
                                        "SubscribeContractResponse"
                                    }
                                    InboundDelegateMsg::ContractNotification(_) => {
                                        "ContractNotification"
                                    }
                                    InboundDelegateMsg::DelegateMessage(_) => "DelegateMessage",
                                    _ => "Unknown",
                                })
                                .collect();
                            // Format as "ApplicationMessages[ApplicationMessage,DelegateMessage]"
                            // when there are inbound messages, or bare "ApplicationMessages" when empty.
                            if tags.is_empty() {
                                "ApplicationMessages".to_string()
                            } else {
                                format!("ApplicationMessages[{}]", tags.join(","))
                            }
                        }
                        freenet_stdlib::client_api::DelegateRequest::RegisterDelegate {
                            ..
                        } => "RegisterDelegate".to_string(),
                        freenet_stdlib::client_api::DelegateRequest::UnregisterDelegate(_) => {
                            "UnregisterDelegate".to_string()
                        }
                        _ => "Unknown".to_string(),
                    })
                } else {
                    None
                };
                if let Some(ref mt) = msg_type {
                    tracing::info!(
                        delegate = %delegate_key,
                        msg_type = %mt,
                        request_id = %request_id,
                        outcome = "queued",
                        "DelegateRequest dispatch"
                    );
                }
                let origin_contract = request.origin_contract;
                // Per-connection user secret namespace (hosted mode). Taken from
                // the OpenRequest, which received it from the connection layer —
                // NOT from anything inside `req`. Moving it into the event keeps
                // it on a channel the delegate/client cannot reach.
                let user_context = request.user_context;

                let res = match op_manager
                    .notify_contract_handler_prioritized(
                        ContractHandlerEvent::DelegateRequest {
                            req,
                            origin_contract,
                            user_context,
                        },
                        crate::contract::Priority::ClientLocal,
                    )
                    .await
                {
                    Ok(ContractHandlerEvent::DelegateResponse(res)) => {
                        if let Some(ref mt) = msg_type {
                            tracing::info!(
                                delegate = %delegate_key,
                                msg_type = %mt,
                                request_id = %request_id,
                                outcome = "executed",
                                "DelegateRequest dispatch"
                            );
                        }
                        res
                    }
                    Err(err) => {
                        tracing::error!(
                            client_id = %client_id,
                            request_id = %request_id,
                            delegate = %delegate_key,
                            error = %err,
                            phase = "error",
                            "Delegate operation failed (contract error)"
                        );
                        return Err(Error::Contract(err));
                    }
                    Ok(_) => {
                        tracing::error!(
                            client_id = %client_id,
                            request_id = %request_id,
                            delegate = %delegate_key,
                            phase = "error",
                            "Delegate operation failed (unexpected state)"
                        );
                        return Err(Error::Op(OpError::UnexpectedOpState));
                    }
                };

                let host_response = Ok(HostResponse::DelegateResponse {
                    key: delegate_key.clone(),
                    values: res,
                });

                if let Some(ch) = &subscription_listener {
                    match ch.try_send(host_response) {
                        Ok(()) => {}
                        Err(tokio::sync::mpsc::error::TrySendError::Full(_)) => {
                            tracing::warn!(
                                client_id = %client_id,
                                request_id = %request_id,
                                delegate = %delegate_key,
                                "Subscription channel full — delegate response dropped"
                            );
                        }
                        Err(tokio::sync::mpsc::error::TrySendError::Closed(_)) => {
                            tracing::error!(
                                client_id = %client_id,
                                request_id = %request_id,
                                delegate = %delegate_key,
                                "Failed to send delegate response — subscription channel closed"
                            );
                        }
                    }
                    return Ok(None);
                }

                // Return the response to be sent by client_event_handling
                return Ok(Some(Either::Left(QueryResult::DelegateResult {
                    key: delegate_key,
                    response: host_response,
                })));
            }
            ClientRequest::Disconnect { .. } => {
                tracing::debug!(
                    client_id = %client_id,
                    request_id = %request_id,
                    "Received disconnect request from client, triggering subscription cleanup"
                );

                // Drop any delegate-notification routing registrations for this
                // client (#3275).
                crate::contract::delegate_app_registry::remove_client(client_id);

                let result = op_manager
                    .ring
                    .remove_client_from_all_subscriptions(client_id);
                for contract in &result.affected_contracts {
                    op_manager.interest_manager.remove_local_client(contract);
                }
                if !result.affected_contracts.is_empty() {
                    tracing::debug!(
                        %client_id,
                        subscriptions_cleaned = result.affected_contracts.len(),
                        "Cleaned up client subscriptions and interest tracking"
                    );
                }

                // Send Unsubscribe upstream for contracts with no remaining interest.
                // FLIP (keystone P6, #4642): the collapse decision is driven by the
                // reconcile controller's strict-farther interest gate
                // (`reconcile_wants_collapse` = `!contract_in_use`), replacing the
                // legacy ANY-downstream `should_unsubscribe_upstream`. The teardown
                // still targets the STORED upstream (narrow flip keeps the flag).
                for contract in &result.affected_contracts {
                    if op_manager.reconcile_wants_collapse(
                        contract,
                        crate::node::network_status::ReconcileShadowSite::Collapse,
                    ) {
                        let op_mgr = op_manager.clone();
                        let contract = *contract;
                        GlobalExecutor::spawn(async move {
                            op_mgr.send_unsubscribe_upstream(&contract).await;
                        });
                    }
                }

                // Notify contract handler to clean up shared_summaries and
                // shared_notifications for this client (fire-and-forget — no response needed).
                if let Err(err) = op_manager.ch_outbound.send_to_handler_fire_and_forget(
                    ContractHandlerEvent::ClientDisconnect { client_id },
                ) {
                    tracing::warn!(
                        %client_id,
                        error = %err,
                        "Failed to notify contract handler of client disconnect"
                    );
                }
            }
            ClientRequest::NodeQueries(query) => {
                tracing::debug!(
                    client_id = %client_id,
                    request_id = %request_id,
                    query = ?query,
                    "Received node query from client"
                );

                let Some(tx) = callback_tx else {
                    tracing::error!(
                        client_id = %client_id,
                        request_id = %request_id,
                        "callback_tx not available for NodeQueries"
                    );
                    unreachable!(
                        "callback_tx should always be Some for NodeQueries based on initialization logic"
                    );
                };

                let node_event = match query {
                    freenet_stdlib::client_api::NodeQuery::ConnectedPeers => {
                        NodeEvent::QueryConnections { callback: tx }
                    }
                    freenet_stdlib::client_api::NodeQuery::SubscriptionInfo => {
                        NodeEvent::QuerySubscriptions { callback: tx }
                    }
                    freenet_stdlib::client_api::NodeQuery::NodeDiagnostics { config } => {
                        NodeEvent::QueryNodeDiagnostics {
                            config,
                            callback: tx,
                        }
                    }
                    freenet_stdlib::client_api::NodeQuery::NeighborHostingInfo => {
                        // TODO: Implement neighbor hosting info query
                        tracing::warn!(
                            client_id = %client_id,
                            request_id = %request_id,
                            "NeighborHostingInfo query not yet implemented"
                        );
                        return Ok(None);
                    }
                };

                if let Err(err) = op_manager.notify_node_event(node_event).await {
                    tracing::error!(
                        client_id = %client_id,
                        request_id = %request_id,
                        error = %err,
                        "notify_node_event error"
                    );
                    return Err(Error::from(err));
                }

                return Ok(Some(Either::Right(callback_rx.unwrap())));
            }
            ClientRequest::Close => {
                return Err(Error::Disconnected);
            }
            ClientRequest::Authenticate { .. } | _ => {
                tracing::error!(
                    client_id = %client_id,
                    request_id = %request_id,
                    "Unsupported operation"
                );
            }
        }
        Ok(None)
    };

    GlobalExecutor::spawn(fut.instrument(tracing::info_span!(
        parent: tracing::Span::current(),
        "process_client_request"
    )))
    .map(|res| match res {
        Ok(Ok(res)) => Ok(res),
        Ok(Err(err)) => Err(err),
        Err(err) => {
            tracing::error!(
                error = %err,
                "Error processing client request (task panic)"
            );
            Err(Error::from(err))
        }
    })
    .boxed()
}

// Re-export mpsc so submodules that use `super::mpsc` still resolve correctly
use tokio::sync::mpsc;
// Re-export Arc for use in this module
use std::sync::Arc;