hydracache-server 0.70.0

Standalone production server daemon for HydraCache.
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
//! Production HC/2 listener backed by the existing verified client dispatch.

use std::collections::BTreeMap;
use std::pin::Pin;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;

use bytes::Bytes;
use futures_util::Stream;
use hydracache_client_hc2::wire::client_envelope;
use hydracache_client_hc2::wire::client_plane_alpha_server::{
    ClientPlaneAlpha, ClientPlaneAlphaServer,
};
use hydracache_client_hc2::wire::invocation_request;
use hydracache_client_hc2::wire::invocation_response;
use hydracache_client_hc2::wire::server_envelope;
use hydracache_client_hc2::wire::{
    BatchResult, CacheEvent, ClientEnvelope, EventGap, HandshakeAck, InvocationRequest,
    InvocationResponse, LockOwnershipResult, LockResult, MutationResult, ResponseMeta,
    ServerEnvelope, SessionHeartbeat, SessionLost, StableErrorCode, SubscriptionAck, ValueResult,
};
use hydracache_client_hc2::{is_supported_hc2_generation, HC2_GENERATION, HC2_MINIMUM_GENERATION};
use hydracache_client_protocol::{
    CasExpectation, ClientErrorCode, ClientRequest, ClientRequestEnvelope, ClientResponse,
    ClientResponseEnvelope, LockConsistency, Namespace, StructuredKey,
};
use hydracache_client_transport_axum::{ClientIdentity, ClientSurfaceState};
use sha2::{Digest, Sha256};
use thiserror::Error;
use tokio::net::TcpListener;
use tokio::sync::{mpsc, watch};
use tokio_stream::wrappers::{ReceiverStream, TcpListenerStream};
use tonic::transport::server::{TcpConnectInfo, TlsConnectInfo};
use tonic::transport::{Certificate, Identity, Server, ServerTlsConfig};
use tonic::{Request, Response, Status, Streaming};

use crate::config::TlsConfig;

/// Opaque, eagerly validated TLS policy for the production HC/2 listener.
#[derive(Clone)]
pub struct Hc2ListenerTls(ServerTlsConfig);

impl std::fmt::Debug for Hc2ListenerTls {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("Hc2ListenerTls")
            .finish_non_exhaustive()
    }
}

impl Hc2ListenerTls {
    /// Read and validate mandatory server identity and client trust roots.
    pub fn from_server_config(tls: &TlsConfig) -> Result<Self, Hc2ServeError> {
        if rustls::crypto::CryptoProvider::get_default().is_none() {
            let _ = rustls::crypto::ring::default_provider().install_default();
        }
        let cert = std::fs::read(tls.cert_path.as_deref().ok_or(Hc2ServeError::MissingTls)?)?;
        let key = std::fs::read(tls.key_path.as_deref().ok_or(Hc2ServeError::MissingTls)?)?;
        let ca = std::fs::read(tls.ca_path.as_deref().ok_or(Hc2ServeError::MissingTls)?)?;
        let config = ServerTlsConfig::new()
            .identity(Identity::from_pem(cert, key))
            .client_ca_root(Certificate::from_pem(ca));
        // Tonic parses the PEM material here. Do this before any listener task
        // starts so malformed identity/trust material cannot follow readiness.
        let _ = Server::builder().tls_config(config.clone())?;
        Ok(Self(config))
    }
}

/// Privacy-safe HC/2 listener accounting used by readiness/drain proofs.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct Hc2AccountingSnapshot {
    /// Currently open authenticated gRPC streams.
    pub active_connections: u64,
    /// Active subscriptions across all streams.
    pub active_subscriptions: u64,
    /// Active fenced sessions across all streams.
    pub active_sessions: u64,
    /// Invocations currently executing through shared dispatch.
    pub pending_invocations: u64,
    /// Frames rejected before dispatch.
    pub rejected_frames: u64,
}

#[derive(Debug, Default)]
struct Accounting {
    active_connections: AtomicU64,
    active_subscriptions: AtomicU64,
    active_sessions: AtomicU64,
    pending_invocations: AtomicU64,
    rejected_frames: AtomicU64,
    next_session: AtomicU64,
    next_watermark: AtomicU64,
}

/// Production gRPC service. Construction requires existing verified dispatch state.
#[derive(Debug, Clone)]
pub struct Hc2ClientPlaneService {
    state: Arc<ClientSurfaceState>,
    cluster_id: Arc<str>,
    accounting: Arc<Accounting>,
}

impl Hc2ClientPlaneService {
    /// Construct a service over the shared HC/1/RESP dispatch state.
    pub fn new(state: Arc<ClientSurfaceState>, cluster_id: impl Into<String>) -> Self {
        Self {
            state,
            cluster_id: Arc::from(cluster_id.into()),
            accounting: Arc::new(Accounting::default()),
        }
    }

    /// Return bounded, secret-free listener accounting.
    pub fn accounting(&self) -> Hc2AccountingSnapshot {
        Hc2AccountingSnapshot {
            active_connections: self.accounting.active_connections.load(Ordering::Acquire),
            active_subscriptions: self.accounting.active_subscriptions.load(Ordering::Acquire),
            active_sessions: self.accounting.active_sessions.load(Ordering::Acquire),
            pending_invocations: self.accounting.pending_invocations.load(Ordering::Acquire),
            rejected_frames: self.accounting.rejected_frames.load(Ordering::Acquire),
        }
    }

    /// Render the production listener's bounded aggregate accounting for the
    /// existing internal Prometheus endpoint.
    ///
    /// The only label has a closed domain. Peer identities, tenant IDs,
    /// authorities, certificate material, keys, and values are never exposed.
    pub fn prometheus_metrics(&self) -> String {
        let snapshot = self.accounting();
        format!(
            concat!(
                "# TYPE hydracache_hc2_connections gauge\n",
                "hydracache_hc2_connections{{transport=\"grpc_bidirectional\"}} {}\n",
                "# TYPE hydracache_hc2_pending_invocations gauge\n",
                "hydracache_hc2_pending_invocations{{transport=\"grpc_bidirectional\"}} {}\n",
                "# TYPE hydracache_hc2_subscriptions gauge\n",
                "hydracache_hc2_subscriptions{{transport=\"grpc_bidirectional\"}} {}\n",
                "# TYPE hydracache_hc2_sessions gauge\n",
                "hydracache_hc2_sessions{{transport=\"grpc_bidirectional\"}} {}\n",
                "# TYPE hydracache_hc2_rejected_frames_total counter\n",
                "hydracache_hc2_rejected_frames_total{{transport=\"grpc_bidirectional\"}} {}\n",
            ),
            snapshot.active_connections,
            snapshot.pending_invocations,
            snapshot.active_subscriptions,
            snapshot.active_sessions,
            snapshot.rejected_frames,
        )
    }
}

type ResponseStream = Pin<Box<dyn Stream<Item = Result<ServerEnvelope, Status>> + Send + 'static>>;

#[tonic::async_trait]
impl ClientPlaneAlpha for Hc2ClientPlaneService {
    type OpenStream = ResponseStream;

    async fn open(
        &self,
        request: Request<Streaming<ClientEnvelope>>,
    ) -> Result<Response<Self::OpenStream>, Status> {
        let peer_id = verified_peer_id(&request)?;
        let mut inbound = request.into_inner();
        let (outbound, receiver) = mpsc::channel(self.state.limits().max_streams_per_connection);
        let service = self.clone();
        tokio::spawn(async move {
            let guard = ConnectionGuard::new(Arc::clone(&service.accounting));
            if let Err(status) = serve_connection(&service, &peer_id, &mut inbound, &outbound).await
            {
                let _ = outbound.send(Err(status)).await;
            }
            drop(guard);
        });
        Ok(Response::new(Box::pin(ReceiverStream::new(receiver))))
    }
}

struct ConnectionGuard {
    accounting: Arc<Accounting>,
}

struct StreamResourceGuard {
    accounting: Arc<Accounting>,
    subscriptions: u64,
    sessions: u64,
}

impl StreamResourceGuard {
    fn new(accounting: Arc<Accounting>) -> Self {
        Self {
            accounting,
            subscriptions: 0,
            sessions: 0,
        }
    }

    fn add_subscription(&mut self) {
        self.subscriptions += 1;
        self.accounting
            .active_subscriptions
            .fetch_add(1, Ordering::AcqRel);
    }

    fn remove_subscription(&mut self) {
        self.subscriptions = self.subscriptions.saturating_sub(1);
        self.accounting
            .active_subscriptions
            .fetch_sub(1, Ordering::AcqRel);
    }

    fn add_session(&mut self) {
        self.sessions += 1;
        self.accounting
            .active_sessions
            .fetch_add(1, Ordering::AcqRel);
    }

    fn remove_session(&mut self) {
        self.sessions = self.sessions.saturating_sub(1);
        self.accounting
            .active_sessions
            .fetch_sub(1, Ordering::AcqRel);
    }
}

impl Drop for StreamResourceGuard {
    fn drop(&mut self) {
        self.accounting
            .active_subscriptions
            .fetch_sub(self.subscriptions, Ordering::AcqRel);
        self.accounting
            .active_sessions
            .fetch_sub(self.sessions, Ordering::AcqRel);
    }
}

impl ConnectionGuard {
    fn new(accounting: Arc<Accounting>) -> Self {
        accounting.active_connections.fetch_add(1, Ordering::AcqRel);
        Self { accounting }
    }
}

impl Drop for ConnectionGuard {
    fn drop(&mut self) {
        self.accounting
            .active_connections
            .fetch_sub(1, Ordering::AcqRel);
    }
}

#[derive(Clone, Copy)]
struct SessionIdentity {
    protocol_generation: u32,
    connection_generation: u64,
}

async fn serve_connection(
    service: &Hc2ClientPlaneService,
    peer_id: &str,
    inbound: &mut Streaming<ClientEnvelope>,
    outbound: &mpsc::Sender<Result<ServerEnvelope, Status>>,
) -> Result<(), Status> {
    let first = inbound
        .message()
        .await?
        .ok_or_else(|| Status::unauthenticated("HC/2 handshake is required"))?;
    let Some(client_envelope::Message::Handshake(handshake)) = first.message else {
        reject(&service.accounting);
        return Err(Status::failed_precondition("HC/2 handshake must be first"));
    };
    if !is_supported_hc2_generation(first.generation)
        || handshake.generation != first.generation
        || first.connection_generation == 0
        || first.connection_generation != handshake.connection_generation
    {
        reject(&service.accounting);
        return Err(Status::failed_precondition("unsupported HC/2 generation"));
    }
    let identity = SessionIdentity {
        protocol_generation: first.generation,
        connection_generation: first.connection_generation,
    };
    outbound
        .send(Ok(server_envelope(
            identity,
            first.correlation_id,
            server_envelope::Message::Handshake(HandshakeAck {
                generation: identity.protocol_generation,
                cluster_id: service.cluster_id.to_string(),
                accepted: handshake.requested,
                topology_epoch: 1,
                connection_generation: identity.connection_generation,
                minimum_generation: HC2_MINIMUM_GENERATION,
                preferred_generation: HC2_GENERATION,
                negotiated_generation_deprecated: identity.protocol_generation < HC2_GENERATION,
            }),
        )))
        .await
        .map_err(|_| Status::cancelled("HC/2 response stream closed"))?;

    let mut subscriptions = BTreeMap::<u64, (Bytes, u64)>::new();
    let mut sessions = BTreeMap::<Bytes, u64>::new();
    let mut resources = StreamResourceGuard::new(Arc::clone(&service.accounting));
    while let Some(envelope) = inbound.message().await? {
        if envelope.generation != identity.protocol_generation
            || envelope.connection_generation != identity.connection_generation
            || envelope.correlation_id == 0
        {
            reject(&service.accounting);
            return Err(Status::failed_precondition(
                "invalid HC/2 envelope identity",
            ));
        }
        match envelope.message {
            Some(client_envelope::Message::Invocation(invocation)) => {
                let event = mutation_event(&invocation);
                let response =
                    dispatch_invocation(service, peer_id, envelope.correlation_id, invocation);
                let mutation_applied = matches!(
                    response.result.as_ref(),
                    Some(invocation_response::Result::Mutation(MutationResult {
                        applied: true
                    }))
                );
                outbound
                    .send(Ok(server_envelope(
                        identity,
                        envelope.correlation_id,
                        server_envelope::Message::Invocation(response),
                    )))
                    .await
                    .map_err(|_| Status::cancelled("HC/2 response stream closed"))?;
                if let Some((key, value, removed)) = event.filter(|_| mutation_applied) {
                    emit_matching_events(
                        service,
                        identity,
                        &key,
                        &value,
                        removed,
                        &mut subscriptions,
                        outbound,
                    )
                    .await?;
                }
            }
            Some(client_envelope::Message::Subscribe(subscribe)) => {
                if subscriptions.contains_key(&subscribe.subscription_id)
                    || subscriptions.len() >= service.state.limits().max_streams_per_connection
                {
                    reject(&service.accounting);
                    return Err(Status::resource_exhausted(
                        "HC/2 subscription bound exceeded",
                    ));
                }
                subscriptions.insert(
                    subscribe.subscription_id,
                    (subscribe.key_prefix, subscribe.resume_watermark),
                );
                resources.add_subscription();
                outbound
                    .send(Ok(server_envelope(
                        identity,
                        envelope.correlation_id,
                        server_envelope::Message::Subscribed(SubscriptionAck {
                            subscription_id: subscribe.subscription_id,
                            watermark: subscribe.resume_watermark,
                        }),
                    )))
                    .await
                    .map_err(|_| Status::cancelled("HC/2 response stream closed"))?;
            }
            Some(client_envelope::Message::Unsubscribe(unsubscribe)) => {
                if subscriptions.remove(&unsubscribe.subscription_id).is_some() {
                    resources.remove_subscription();
                }
            }
            Some(client_envelope::Message::SessionOpen(_)) => {
                let sequence = service
                    .accounting
                    .next_session
                    .fetch_add(1, Ordering::AcqRel)
                    + 1;
                let session_id = Bytes::copy_from_slice(&sequence.to_be_bytes());
                sessions.insert(session_id.clone(), 1);
                resources.add_session();
                outbound
                    .send(Ok(server_envelope(
                        identity,
                        envelope.correlation_id,
                        server_envelope::Message::SessionHeartbeat(SessionHeartbeat {
                            session_id,
                            fence: 1,
                        }),
                    )))
                    .await
                    .map_err(|_| Status::cancelled("HC/2 response stream closed"))?;
            }
            Some(client_envelope::Message::SessionHeartbeat(heartbeat)) => {
                let message = if sessions.get(&heartbeat.session_id) == Some(&heartbeat.fence) {
                    server_envelope::Message::SessionHeartbeat(heartbeat)
                } else {
                    server_envelope::Message::SessionLost(SessionLost {
                        session_id: heartbeat.session_id,
                        last_fence: heartbeat.fence,
                    })
                };
                outbound
                    .send(Ok(server_envelope(
                        identity,
                        envelope.correlation_id,
                        message,
                    )))
                    .await
                    .map_err(|_| Status::cancelled("HC/2 response stream closed"))?;
            }
            Some(client_envelope::Message::SessionClose(close)) => {
                if sessions.remove(&close.session_id).is_some() {
                    resources.remove_session();
                }
            }
            Some(client_envelope::Message::Cancel(_)) => {}
            Some(client_envelope::Message::Handshake(_)) | None => {
                reject(&service.accounting);
                return Err(Status::failed_precondition("unexpected HC/2 frame"));
            }
        }
    }
    Ok(())
}

fn dispatch_invocation(
    service: &Hc2ClientPlaneService,
    peer_id: &str,
    correlation_id: u64,
    invocation: InvocationRequest,
) -> InvocationResponse {
    service
        .accounting
        .pending_invocations
        .fetch_add(1, Ordering::AcqRel);
    let response = dispatch_invocation_inner(service, peer_id, correlation_id, invocation);
    service
        .accounting
        .pending_invocations
        .fetch_sub(1, Ordering::AcqRel);
    response
}

fn dispatch_invocation_inner(
    service: &Hc2ClientPlaneService,
    peer_id: &str,
    correlation_id: u64,
    invocation: InvocationRequest,
) -> InvocationResponse {
    let Some(meta) = invocation.meta else {
        return wire_error(
            StableErrorCode::StableErrorInvalidRequest,
            "request metadata is required",
        );
    };
    if meta.tenant.trim().is_empty() {
        return wire_error(
            StableErrorCode::StableErrorUnauthenticated,
            "tenant is required",
        );
    }
    if meta.deadline_unix_ms != 0 && meta.deadline_unix_ms <= unix_time_ms() {
        return wire_error(
            StableErrorCode::StableErrorDeadlineExceeded,
            "deadline expired",
        );
    }
    let identity = match ClientIdentity::new(peer_id, meta.tenant.clone()) {
        Ok(identity) => identity,
        Err(_) => {
            return wire_error(
                StableErrorCode::StableErrorUnauthenticated,
                "invalid identity",
            )
        }
    };
    let Some(operation) = invocation.operation else {
        return wire_error(
            StableErrorCode::StableErrorInvalidRequest,
            "operation is required",
        );
    };
    if let invocation_request::Operation::Batch(batch) = operation {
        let items = batch
            .items
            .into_iter()
            .map(|item| {
                let nested = InvocationRequest {
                    meta: Some(meta.clone()),
                    operation: item.operation.map(batch_operation),
                };
                dispatch_invocation_inner(service, peer_id, correlation_id, nested)
            })
            .collect();
        return wire_success(Some(invocation_response::Result::Batch(BatchResult {
            items,
        })));
    }
    let request = match to_client_request(operation) {
        Ok(request) => request,
        Err(detail) => return wire_error(StableErrorCode::StableErrorInvalidRequest, detail),
    };
    let mut envelope = ClientRequestEnvelope::new(correlation_id.to_string(), request);
    if meta.deadline_unix_ms != 0 {
        envelope = envelope.with_deadline_ms(meta.deadline_unix_ms);
    }
    if !meta.idempotency_key.is_empty() {
        envelope = envelope.with_idempotency_key(hex(&meta.idempotency_key));
    }
    from_dispatch_response(service.state.dispatch_verified_request(&identity, envelope))
}

fn batch_operation(
    operation: hydracache_client_hc2::wire::batch_item::Operation,
) -> invocation_request::Operation {
    match operation {
        hydracache_client_hc2::wire::batch_item::Operation::Get(value) => {
            invocation_request::Operation::Get(value)
        }
        hydracache_client_hc2::wire::batch_item::Operation::Put(value) => {
            invocation_request::Operation::Put(value)
        }
        hydracache_client_hc2::wire::batch_item::Operation::Delete(value) => {
            invocation_request::Operation::Delete(value)
        }
        hydracache_client_hc2::wire::batch_item::Operation::CompareAndSet(value) => {
            invocation_request::Operation::CompareAndSet(value)
        }
    }
}

fn to_client_request(
    operation: invocation_request::Operation,
) -> Result<ClientRequest, &'static str> {
    let ns = Namespace::new("hc2").map_err(|_| "invalid namespace")?;
    Ok(match operation {
        invocation_request::Operation::Get(value) => ClientRequest::Get {
            ns,
            key: structured_key(&value.key)?,
        },
        invocation_request::Operation::Put(value) => ClientRequest::Put {
            ns,
            key: structured_key(&value.key)?,
            value: value.value.to_vec(),
            ttl_ms: (value.ttl_ms != 0).then_some(value.ttl_ms),
            dimensions: Vec::new(),
        },
        invocation_request::Operation::Delete(value) => ClientRequest::Invalidate {
            ns,
            key: structured_key(&value.key)?,
        },
        invocation_request::Operation::CompareAndSet(value) => ClientRequest::CompareAndSet {
            ns,
            key: structured_key(&value.key)?,
            expected: CasExpectation::Exact(value.expected.to_vec()),
            new_value: value.replacement.to_vec(),
            level: LockConsistency::Quorum,
        },
        invocation_request::Operation::TryLock(value) => ClientRequest::TryLock {
            ns,
            key: structured_key(&value.key)?,
            lease_ms: value.lease_ms,
            wait_ms: value.wait_ms,
            level: LockConsistency::Quorum,
        },
        invocation_request::Operation::Unlock(value) => ClientRequest::Unlock {
            ns,
            key: structured_key(&value.key)?,
            fence: value.fence,
        },
        invocation_request::Operation::RenewLock(value) => ClientRequest::RenewLockLease {
            ns,
            key: structured_key(&value.key)?,
            fence: value.fence,
            lease_ms: value.lease_ms,
        },
        invocation_request::Operation::LockOwnership(value) => ClientRequest::GetLockOwnership {
            ns,
            key: structured_key(&value.key)?,
        },
        invocation_request::Operation::RemoveIfValue(value) => ClientRequest::RemoveIfValue {
            ns,
            key: structured_key(&value.key)?,
            expected: value.expected.to_vec(),
            level: LockConsistency::Quorum,
        },
        invocation_request::Operation::Batch(_) => return Err("nested batch is not allowed"),
    })
}

fn from_dispatch_response(response: ClientResponseEnvelope) -> InvocationResponse {
    match response.result {
        Ok(ClientResponse::Value { value }) => {
            wire_success(Some(invocation_response::Result::Value(ValueResult {
                found: value.is_some(),
                value: value.unwrap_or_default().into(),
                expires_at_unix_ms: 0,
            })))
        }
        Ok(ClientResponse::Stored | ClientResponse::Invalidated) => wire_success(Some(
            invocation_response::Result::Mutation(MutationResult { applied: true }),
        )),
        Ok(ClientResponse::CasApplied { .. }) => wire_success(Some(
            invocation_response::Result::Mutation(MutationResult { applied: true }),
        )),
        Ok(ClientResponse::CasMismatch { .. }) => wire_success(Some(
            invocation_response::Result::Mutation(MutationResult { applied: false }),
        )),
        Ok(ClientResponse::LockAcquired { fence }) => {
            wire_success(Some(invocation_response::Result::Lock(LockResult {
                acquired: true,
                fence,
            })))
        }
        Ok(ClientResponse::LockBusy) => {
            wire_success(Some(invocation_response::Result::Lock(LockResult {
                acquired: false,
                fence: 0,
            })))
        }
        Ok(ClientResponse::LockReleased | ClientResponse::LockLeaseRenewed) => wire_success(Some(
            invocation_response::Result::Mutation(MutationResult { applied: true }),
        )),
        Ok(ClientResponse::LockOwnership { fence, locked }) => wire_success(Some(
            invocation_response::Result::LockOwnership(LockOwnershipResult {
                locked,
                fence: fence.unwrap_or_default(),
            }),
        )),
        Ok(_) => wire_error(
            StableErrorCode::StableErrorUnsupported,
            "unsupported HC/2 result",
        ),
        Err(error) => wire_error(map_client_error(error.code), "request rejected"),
    }
}

fn map_client_error(code: ClientErrorCode) -> StableErrorCode {
    match code {
        ClientErrorCode::Unauthenticated => StableErrorCode::StableErrorUnauthenticated,
        ClientErrorCode::Unauthorized | ClientErrorCode::ResidencyDenied => {
            StableErrorCode::StableErrorUnauthorized
        }
        ClientErrorCode::TenantQuota | ClientErrorCode::RateLimited | ClientErrorCode::TooLarge => {
            StableErrorCode::StableErrorQuotaExceeded
        }
        ClientErrorCode::DeadlineExceeded => StableErrorCode::StableErrorDeadlineExceeded,
        ClientErrorCode::Conflict => StableErrorCode::StableErrorConflict,
        ClientErrorCode::BackendUnavailable => StableErrorCode::StableErrorUnavailable,
        ClientErrorCode::IncompatibleVersion | ClientErrorCode::MalformedFrame => {
            StableErrorCode::StableErrorInvalidRequest
        }
    }
}

fn wire_success(result: Option<invocation_response::Result>) -> InvocationResponse {
    InvocationResponse {
        meta: Some(ResponseMeta {
            error: StableErrorCode::StableErrorUnspecified as i32,
            retry: hydracache_client_hc2::wire::RetryDirective::Never as i32,
            safe_detail: String::new(),
            topology_epoch: 1,
        }),
        result,
    }
}

fn wire_error(code: StableErrorCode, detail: &'static str) -> InvocationResponse {
    InvocationResponse {
        meta: Some(ResponseMeta {
            error: code as i32,
            retry: hydracache_client_hc2::wire::RetryDirective::Never as i32,
            safe_detail: detail.to_owned(),
            topology_epoch: 1,
        }),
        result: None,
    }
}

async fn emit_matching_events(
    service: &Hc2ClientPlaneService,
    identity: SessionIdentity,
    key: &[u8],
    value: &[u8],
    removed: bool,
    subscriptions: &mut BTreeMap<u64, (Bytes, u64)>,
    outbound: &mpsc::Sender<Result<ServerEnvelope, Status>>,
) -> Result<(), Status> {
    for (subscription_id, (prefix, watermark)) in subscriptions.iter_mut() {
        if key.starts_with(prefix) {
            let next = service
                .accounting
                .next_watermark
                .fetch_add(1, Ordering::AcqRel)
                + 1;
            if *watermark != 0 && next > watermark.saturating_add(1) {
                outbound
                    .send(Ok(server_envelope(
                        identity,
                        0,
                        server_envelope::Message::Gap(EventGap {
                            subscription_id: *subscription_id,
                            after_watermark: *watermark,
                        }),
                    )))
                    .await
                    .map_err(|_| Status::cancelled("HC/2 response stream closed"))?;
            }
            *watermark = next;
            outbound
                .send(Ok(server_envelope(
                    identity,
                    0,
                    server_envelope::Message::Event(CacheEvent {
                        subscription_id: *subscription_id,
                        watermark: next,
                        key: Bytes::copy_from_slice(key),
                        value: Bytes::copy_from_slice(value),
                        removed,
                    }),
                )))
                .await
                .map_err(|_| Status::cancelled("HC/2 response stream closed"))?;
        }
    }
    Ok(())
}

fn mutation_event(invocation: &InvocationRequest) -> Option<(Bytes, Bytes, bool)> {
    match invocation.operation.as_ref()? {
        invocation_request::Operation::Put(value) => {
            Some((value.key.clone(), value.value.clone(), false))
        }
        invocation_request::Operation::Delete(value) => {
            Some((value.key.clone(), Bytes::new(), true))
        }
        invocation_request::Operation::CompareAndSet(value) => {
            Some((value.key.clone(), value.replacement.clone(), false))
        }
        invocation_request::Operation::TryLock(_)
        | invocation_request::Operation::Unlock(_)
        | invocation_request::Operation::RenewLock(_)
        | invocation_request::Operation::LockOwnership(_) => None,
        invocation_request::Operation::RemoveIfValue(value) => {
            Some((value.key.clone(), Bytes::new(), true))
        }
        _ => None,
    }
}

fn structured_key(value: &[u8]) -> Result<StructuredKey, &'static str> {
    if value.is_empty() {
        return Err("key is required");
    }
    StructuredKey::new(vec![hex(value)]).map_err(|_| "invalid key")
}

fn server_envelope(
    identity: SessionIdentity,
    correlation_id: u64,
    message: server_envelope::Message,
) -> ServerEnvelope {
    ServerEnvelope {
        generation: identity.protocol_generation,
        connection_generation: identity.connection_generation,
        correlation_id,
        message: Some(message),
    }
}

fn reject(accounting: &Accounting) {
    accounting.rejected_frames.fetch_add(1, Ordering::Relaxed);
}

fn verified_peer_id(request: &Request<Streaming<ClientEnvelope>>) -> Result<String, Status> {
    let connect = request
        .extensions()
        .get::<TlsConnectInfo<TcpConnectInfo>>()
        .ok_or_else(|| Status::unauthenticated("verified mTLS peer is required"))?;
    let certificates = connect
        .peer_certs()
        .ok_or_else(|| Status::unauthenticated("client certificate is required"))?;
    let certificate = certificates
        .first()
        .ok_or_else(|| Status::unauthenticated("client certificate is required"))?;
    Ok(format!(
        "mtls-sha256:{}",
        hex(&Sha256::digest(certificate.as_ref()))
    ))
}

fn hex(bytes: &[u8]) -> String {
    use std::fmt::Write;
    let mut encoded = String::with_capacity(bytes.len() * 2);
    for byte in bytes {
        let _ = write!(&mut encoded, "{byte:02x}");
    }
    encoded
}

fn unix_time_ms() -> u64 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap_or_default()
        .as_millis()
        .try_into()
        .unwrap_or(u64::MAX)
}

/// Serve the already-bound production listener with mandatory client certificates.
pub async fn serve_hc2_listener(
    listener: TcpListener,
    service: Hc2ClientPlaneService,
    tls: Hc2ListenerTls,
    mut shutdown: watch::Receiver<bool>,
) -> Result<(), Hc2ServeError> {
    Server::builder()
        .tls_config(tls.0)?
        .add_service(
            ClientPlaneAlphaServer::new(service)
                .max_decoding_message_size(8 * 1024 * 1024)
                .max_encoding_message_size(8 * 1024 * 1024),
        )
        .serve_with_incoming_shutdown(TcpListenerStream::new(listener), async move {
            while shutdown.changed().await.is_ok() {
                if *shutdown.borrow() {
                    break;
                }
            }
        })
        .await?;
    Ok(())
}

/// Fail-loud HC/2 listener startup/runtime errors.
#[derive(Debug, Error)]
pub enum Hc2ServeError {
    /// HC/2 was enabled without complete TLS paths.
    #[error("HC/2 requires certificate, key, and client CA paths")]
    MissingTls,
    /// TLS material could not be read.
    #[error("failed to read HC/2 TLS material: {0}")]
    Io(#[from] std::io::Error),
    /// Tonic rejected TLS or serving configuration.
    #[error("HC/2 gRPC serving failed: {0}")]
    Transport(#[from] tonic::transport::Error),
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::path::PathBuf;
    use std::time::Duration;

    use hydracache_client_hc2::wire::{
        GetRequest, LockOwnershipRequest, PutRequest, RemoveIfValueRequest, RequestMeta,
        TryLockRequest, UnlockRequest,
    };
    use hydracache_client_hc2::{
        ClientConfig, ErrorCode, GrpcMtlsAdapter, GrpcMtlsConfig, Hc2Client, SubscriptionEvent,
    };
    use rcgen::{
        BasicConstraints, CertificateParams, CertifiedIssuer, ExtendedKeyUsagePurpose, IsCa,
        KeyPair,
    };
    use tokio::io::{AsyncReadExt, AsyncWriteExt};

    fn service() -> Hc2ClientPlaneService {
        Hc2ClientPlaneService::new(
            Arc::new(ClientSurfaceState::new(Default::default()).unwrap()),
            "test-cluster",
        )
    }

    fn meta() -> RequestMeta {
        RequestMeta {
            deadline_unix_ms: 0,
            idempotency_key: Bytes::new(),
            tenant: "tenant-a".to_owned(),
            topology_epoch: 1,
        }
    }

    #[test]
    fn operations_use_the_existing_verified_dispatch_state() {
        let service = service();
        let put = dispatch_invocation(
            &service,
            "verified-peer",
            1,
            InvocationRequest {
                meta: Some(meta()),
                operation: Some(invocation_request::Operation::Put(PutRequest {
                    key: Bytes::from_static(b"key"),
                    value: Bytes::from_static(b"value"),
                    ttl_ms: 0,
                })),
            },
        );
        assert!(matches!(
            put.result,
            Some(invocation_response::Result::Mutation(MutationResult {
                applied: true
            }))
        ));
        let get = dispatch_invocation(
            &service,
            "verified-peer",
            2,
            InvocationRequest {
                meta: Some(meta()),
                operation: Some(invocation_request::Operation::Get(GetRequest {
                    key: Bytes::from_static(b"key"),
                })),
            },
        );
        assert!(matches!(
            get.result,
            Some(invocation_response::Result::Value(ValueResult { found: true, ref value, .. }))
                if value.as_ref() == b"value"
        ));
        assert_eq!(service.state.dispatch_attempts(), 2);
        assert_eq!(service.state.state_mutations(), 1);
        assert_eq!(service.accounting(), Hc2AccountingSnapshot::default());
    }

    #[test]
    fn conditional_remove_and_fenced_lock_use_the_shared_dispatch() {
        let service = service();
        let invoke = |correlation_id, operation| {
            dispatch_invocation(
                &service,
                "verified-peer",
                correlation_id,
                InvocationRequest {
                    meta: Some(meta()),
                    operation: Some(operation),
                },
            )
        };
        invoke(
            1,
            invocation_request::Operation::Put(PutRequest {
                key: Bytes::from_static(b"key"),
                value: Bytes::from_static(b"value"),
                ttl_ms: 0,
            }),
        );
        let mismatch = invoke(
            2,
            invocation_request::Operation::RemoveIfValue(RemoveIfValueRequest {
                key: Bytes::from_static(b"key"),
                expected: Bytes::from_static(b"wrong"),
            }),
        );
        assert!(matches!(
            mismatch.result,
            Some(invocation_response::Result::Mutation(MutationResult {
                applied: false
            }))
        ));
        let removed = invoke(
            3,
            invocation_request::Operation::RemoveIfValue(RemoveIfValueRequest {
                key: Bytes::from_static(b"key"),
                expected: Bytes::from_static(b"value"),
            }),
        );
        assert!(matches!(
            removed.result,
            Some(invocation_response::Result::Mutation(MutationResult {
                applied: true
            }))
        ));

        let acquired = invoke(
            4,
            invocation_request::Operation::TryLock(TryLockRequest {
                key: Bytes::from_static(b"lock"),
                lease_ms: 10_000,
                wait_ms: 0,
            }),
        );
        let fence = match acquired.result {
            Some(invocation_response::Result::Lock(LockResult {
                acquired: true,
                fence,
            })) => fence,
            other => panic!("expected acquired lock, got {other:?}"),
        };
        assert_ne!(fence, 0);
        let ownership = invoke(
            5,
            invocation_request::Operation::LockOwnership(LockOwnershipRequest {
                key: Bytes::from_static(b"lock"),
            }),
        );
        assert!(matches!(
            ownership.result,
            Some(invocation_response::Result::LockOwnership(
                LockOwnershipResult {
                    locked: true,
                    fence: observed,
                }
            )) if observed == fence
        ));
        let released = invoke(
            6,
            invocation_request::Operation::Unlock(UnlockRequest {
                key: Bytes::from_static(b"lock"),
                fence,
            }),
        );
        assert!(matches!(
            released.result,
            Some(invocation_response::Result::Mutation(MutationResult {
                applied: true
            }))
        ));
    }

    #[test]
    fn prometheus_accounting_has_only_bounded_privacy_safe_labels() {
        let service = service();
        service
            .accounting
            .active_connections
            .store(2, Ordering::Release);
        service
            .accounting
            .active_subscriptions
            .store(3, Ordering::Release);
        service
            .accounting
            .active_sessions
            .store(4, Ordering::Release);
        service
            .accounting
            .pending_invocations
            .store(5, Ordering::Release);
        service
            .accounting
            .rejected_frames
            .store(6, Ordering::Release);

        let metrics = service.prometheus_metrics();
        assert!(metrics.contains("hydracache_hc2_connections{transport=\"grpc_bidirectional\"} 2"));
        assert!(metrics
            .contains("hydracache_hc2_pending_invocations{transport=\"grpc_bidirectional\"} 5"));
        assert!(metrics
            .contains("hydracache_hc2_rejected_frames_total{transport=\"grpc_bidirectional\"} 6"));
        for forbidden in [
            "tenant-a",
            "verified-peer",
            "test-cluster",
            "endpoint",
            "authority",
            "certificate",
        ] {
            assert!(!metrics.contains(forbidden));
        }
    }

    #[test]
    fn missing_tenant_and_expired_deadline_fail_before_dispatch() {
        let service = service();
        let mut missing = meta();
        missing.tenant.clear();
        let response = dispatch_invocation(
            &service,
            "verified-peer",
            1,
            InvocationRequest {
                meta: Some(missing),
                operation: Some(invocation_request::Operation::Get(GetRequest {
                    key: Bytes::from_static(b"key"),
                })),
            },
        );
        assert_eq!(
            response.meta.unwrap().error,
            StableErrorCode::StableErrorUnauthenticated as i32
        );
        let mut expired = meta();
        expired.deadline_unix_ms = 1;
        let response = dispatch_invocation(
            &service,
            "verified-peer",
            2,
            InvocationRequest {
                meta: Some(expired),
                operation: Some(invocation_request::Operation::Get(GetRequest {
                    key: Bytes::from_static(b"key"),
                })),
            },
        );
        assert_eq!(
            response.meta.unwrap().error,
            StableErrorCode::StableErrorDeadlineExceeded as i32
        );
        assert_eq!(service.state.dispatch_attempts(), 0);
    }

    struct TestPki {
        ca: String,
        server_cert: String,
        server_key: String,
        client_cert: String,
        client_key: String,
    }

    fn test_pki() -> TestPki {
        let mut ca_params = CertificateParams::new(Vec::<String>::new()).unwrap();
        ca_params.is_ca = IsCa::Ca(BasicConstraints::Unconstrained);
        let ca = CertifiedIssuer::self_signed(ca_params, KeyPair::generate().unwrap()).unwrap();

        let server_key = KeyPair::generate().unwrap();
        let mut server_params = CertificateParams::new(vec!["localhost".to_owned()]).unwrap();
        server_params.extended_key_usages = vec![ExtendedKeyUsagePurpose::ServerAuth];
        let server_cert = server_params.signed_by(&server_key, &ca).unwrap();

        let client_key = KeyPair::generate().unwrap();
        let mut client_params = CertificateParams::new(vec!["hc2-client".to_owned()]).unwrap();
        client_params.extended_key_usages = vec![ExtendedKeyUsagePurpose::ClientAuth];
        let client_cert = client_params.signed_by(&client_key, &ca).unwrap();
        TestPki {
            ca: ca.pem(),
            server_cert: server_cert.pem(),
            server_key: server_key.serialize_pem(),
            client_cert: client_cert.pem(),
            client_key: client_key.serialize_pem(),
        }
    }

    fn write_tls(root: &PathBuf, pki: &TestPki) -> TlsConfig {
        std::fs::create_dir_all(root).unwrap();
        let cert = root.join("server.pem");
        let key = root.join("server.key");
        let ca = root.join("clients.pem");
        std::fs::write(&cert, &pki.server_cert).unwrap();
        std::fs::write(&key, &pki.server_key).unwrap();
        std::fs::write(&ca, &pki.ca).unwrap();
        TlsConfig {
            enabled: true,
            cert_path: Some(cert),
            key_path: Some(key),
            ca_path: Some(ca),
            acknowledge_insecure: false,
        }
    }

    fn adapter(addr: std::net::SocketAddr, server: &TestPki, client: &TestPki) -> GrpcMtlsAdapter {
        GrpcMtlsAdapter::new(
            GrpcMtlsConfig::new(
                format!("https://{addr}"),
                "localhost",
                server.ca.as_bytes(),
                client.client_cert.as_bytes(),
                client.client_key.as_bytes(),
            )
            .unwrap(),
        )
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn real_socket_requires_mtls_dispatches_pushes_and_drains_to_zero() {
        let _ = rustls::crypto::ring::default_provider().install_default();
        let unique = unix_time_ms();
        let root = PathBuf::from(format!(
            "target/test-hc2-production-{}-{unique}",
            std::process::id()
        ));
        let trusted = test_pki();
        let untrusted = test_pki();
        let tls = Hc2ListenerTls::from_server_config(&write_tls(&root, &trusted)).unwrap();
        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        let service = service();
        let observed = service.clone();
        let (shutdown_tx, shutdown_rx) = watch::channel(false);
        let serving =
            tokio::spawn(
                async move { serve_hc2_listener(listener, service, tls, shutdown_rx).await },
            );

        let mut plaintext = tokio::net::TcpStream::connect(addr).await.unwrap();
        plaintext
            .write_all(b"PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n")
            .await
            .unwrap();
        let mut byte = [0_u8; 1];
        let plaintext_result =
            tokio::time::timeout(Duration::from_secs(1), plaintext.read(&mut byte)).await;
        assert!(
            matches!(plaintext_result, Ok(Ok(0)) | Ok(Err(_)))
                || matches!(plaintext_result, Ok(Ok(1))) && byte[0] == 21,
            "plaintext must be rejected before protocol dispatch: {plaintext_result:?}"
        );

        let rejected = Hc2Client::connect(
            &adapter(addr, &trusted, &untrusted),
            ClientConfig::new("untrusted", "tenant-a"),
        )
        .await
        .expect_err("foreign client CA must fail closed");
        assert_eq!(rejected.code(), ErrorCode::Unavailable);

        let client = Hc2Client::connect(
            &adapter(addr, &trusted, &trusted),
            ClientConfig::new("claimed-name-is-not-identity", "tenant-a"),
        )
        .await
        .unwrap();
        assert_eq!(client.cluster_id(), "test-cluster");
        let mut subscription = client
            .subscribe(Bytes::from_static(b"event/"), 0)
            .await
            .unwrap();
        let session = client.open_session(Duration::from_secs(2)).await.unwrap();
        assert_eq!(session.fence().unwrap(), 1);
        let active_client = client.retained_state();
        assert_eq!(active_client.active_subscriptions, 1);
        assert_eq!(active_client.active_sessions, 1);
        client
            .put(
                Bytes::from_static(b"event/key"),
                Bytes::from_static(b"value"),
                None,
                None,
            )
            .await
            .unwrap();
        let value = client
            .get(Bytes::from_static(b"event/key"), None)
            .await
            .unwrap()
            .expect("stored value");
        assert_eq!(value.value, Bytes::from_static(b"value"));
        assert!(matches!(
            tokio::time::timeout(Duration::from_secs(1), subscription.next())
                .await
                .unwrap(),
            Some(SubscriptionEvent::Event(_))
        ));
        // Tear down the transport while stream-owned resources are still live.
        // Server accounting must be released by the stream guard rather than
        // depending on cooperative unsubscribe/session-close frames.
        client.close();
        drop(subscription);
        drop(session);
        let closed_client = client.retained_state();
        assert!(closed_client.closed);
        assert_eq!(closed_client.pending_invocations, 0);
        assert_eq!(closed_client.pending_subscriptions, 0);
        assert_eq!(closed_client.active_subscriptions, 0);
        assert_eq!(closed_client.pending_sessions, 0);
        assert_eq!(closed_client.active_sessions, 0);
        assert_eq!(
            closed_client.available_invocation_permits,
            ClientConfig::new("limits", "tenant-a")
                .limits
                .max_pending_invocations
        );
        assert_eq!(
            closed_client.available_subscription_permits,
            ClientConfig::new("limits", "tenant-a")
                .limits
                .max_subscriptions
        );
        assert_eq!(
            closed_client.available_session_permits,
            ClientConfig::new("limits", "tenant-a").limits.max_sessions
        );

        for _ in 0..50 {
            if observed.accounting() == Hc2AccountingSnapshot::default() {
                break;
            }
            tokio::time::sleep(Duration::from_millis(10)).await;
        }
        assert_eq!(observed.accounting(), Hc2AccountingSnapshot::default());

        for cardinality in [1_usize, 10, 100] {
            let mut clients = Vec::with_capacity(cardinality);
            for index in 0..cardinality {
                let client = Hc2Client::connect(
                    &adapter(addr, &trusted, &trusted),
                    ClientConfig::new(
                        format!("retention-series-{cardinality}-{index}"),
                        "tenant-a",
                    ),
                )
                .await
                .unwrap();
                clients.push(client);
            }
            for _ in 0..100 {
                if observed.accounting().active_connections == cardinality as u64 {
                    break;
                }
                tokio::time::sleep(Duration::from_millis(10)).await;
            }
            assert_eq!(
                observed.accounting(),
                Hc2AccountingSnapshot {
                    active_connections: cardinality as u64,
                    ..Hc2AccountingSnapshot::default()
                }
            );
            for client in &clients {
                let retained = client.retained_state();
                assert_eq!(retained.pending_invocations, 0);
                assert_eq!(retained.pending_subscriptions, 0);
                assert_eq!(retained.active_subscriptions, 0);
                assert_eq!(retained.pending_sessions, 0);
                assert_eq!(retained.active_sessions, 0);
                client.close();
            }
            drop(clients);
            for _ in 0..100 {
                if observed.accounting() == Hc2AccountingSnapshot::default() {
                    break;
                }
                tokio::time::sleep(Duration::from_millis(10)).await;
            }
            assert_eq!(observed.accounting(), Hc2AccountingSnapshot::default());
        }
        shutdown_tx.send(true).unwrap();
        serving.await.unwrap().unwrap();
        std::fs::remove_dir_all(root).unwrap();
    }
}