praxis-proxy-filter 0.5.6

Filter pipeline engine and built-in filters for Praxis
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
// SPDX-License-Identifier: Apache-2.0
// Copyright (c) 2026 Praxis Contributors

//! Reusable execution of a filtered HTTP sub-request.
//!
//! [`FilteredSubrequestExecutor`] runs a single named filter pipeline against a
//! sub-request and returns owned continuation state: it reconstructs a nested
//! [`HttpFilterContext`](crate::HttpFilterContext), runs the request, request-body,
//! response, and (for buffered responses) response-body phases, applies the same
//! forwarding boundary as the normal upstream path, dispatches the transport in
//! either buffered or streaming mode, and captures a
//! [`FilteredSubrequestContinuation`] the caller drives to completion.
//!
//! The executor owns three transient extension mechanisms end-to-end —
//! [`RetainedFilterResults`], [`PendingStreamChunks`], and
//! [`StreamTermination`] — and recognizes two framework-defined caller-staged
//! channels: [`PendingCredentials`], which it drains to materialize each
//! authority-bound secret only after resolving the destination (see
//! [`DeferredCredential`](crate::DeferredCredential)), and [`StagedUpstream`],
//! which it drains to seed the sub-request's upstream before the request phase so
//! a callout can dial a known destination without an upstream-selecting filter.
//! It otherwise never
//! inspects caller-injected extension types. Callers that stash their own state
//! in the request extensions recover it from
//! [`FilteredSubrequestError::into_parts`],
//! [`FilteredSubrequestContinuation::into_parent_extensions`], or
//! [`FilteredSubrequestContinuation::into_completion`], and strip it themselves.
//!
//! Retained-state accounting is delegated to the caller through the
//! [`RetainedStateAccounting`] hook so the executor stays independent of any
//! particular caller's state layout while still enforcing a ceiling at every
//! phase boundary.

mod context;
mod continuation;
mod sanitize;
mod streaming;
#[cfg(test)]
#[expect(clippy::allow_attributes, reason = "blanket test suppressions")]
#[allow(
    clippy::unwrap_used,
    clippy::expect_used,
    clippy::panic,
    clippy::too_many_lines,
    reason = "tests"
)]
mod tests;
mod transport;

use std::{
    net::SocketAddr,
    sync::{
        Arc,
        atomic::{AtomicBool, Ordering},
    },
    time::{Duration, Instant},
};

use bytes::Bytes;
use http::HeaderMap;
use praxis_core::{
    config::{CachedClusterTls, ClusterTls},
    connectivity::{ConnectionOptions, PreparedTarget, Upstream},
    subrequest::{FrameworkHeaders, StreamLimits, SubRequestError, SubResponseBody},
};
use tracing::{Instrument as _, warn};

use self::{
    context::{SubrequestRuntimeResources, build_sub_filter_context},
    sanitize::{
        apply_pre_read_header_mutations, apply_request_header_mutations, body_exceeds_limit, ensure_destination_host,
        response_body_overflow_limit, sanitize_subrequest_headers, sanitize_subresponse_headers, set_authority_host,
        streaming_transport_limit, strip_reserved_headers, subresponse_from_rejection,
    },
    transport::{build_peer, classify_transport_failure, stream_termination_cause},
};
pub(crate) use self::{
    continuation::{FilteredSubrequestContinuation, SubrequestCompletion},
    sanitize::normalize_response_status,
    streaming::{CalloutStreamingBody, FilteredStreamingBody},
};
use crate::{
    FilterAction, FilterError, FilterPipeline, StreamTermination, StreamTerminationCause, SubRequest,
    SubRequestResponseMode, SubResponse,
    actions::Rejection,
    context::PendingStreamChunks,
    credentials::{PendingCredentials, ResolvedDestination},
    extensions::RequestExtensions,
    results::RetainedFilterResults,
};

/// Idle timeout applied to a streaming sub-request transport.
///
/// The absolute per-step deadline still bounds total duration; this only
/// caps the gap between upstream chunks so a stalled source is abandoned.
pub(crate) const STREAMING_IDLE_TIMEOUT: Duration = Duration::from_secs(30);

/// Caller-supplied accounting for retained sub-request state.
///
/// The executor enforces a ceiling on caller-owned retained state at every
/// phase boundary without knowing how that state is represented. Callers
/// implement this to report, from the live request extensions, whether their
/// retained footprint currently exceeds the limit.
pub(crate) trait RetainedStateAccounting {
    /// Whether the caller-owned retained state currently exceeds its ceiling.
    fn exceeds_limit(&self, extensions: &RequestExtensions) -> bool;
}

/// Where a captured sub-response originated.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum ResponseOrigin {
    /// A real upstream produced the response.
    Upstream,
    /// A nested filter produced the response locally.
    Local,
    /// A transport failure was synthesized into a response.
    Transport,
}

/// Transport failure classification used to synthesize a gateway response.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum TransportFailure {
    /// Admission control timed out before dispatch.
    AdmissionTimeout,
    /// The circuit breaker was open.
    CircuitOpen,
    /// The connection could not be established.
    Connect,
    /// A generic I/O failure occurred.
    Io,
    /// The transport deadline was exceeded.
    DeadlineExceeded,
    /// The response exceeded the configured size limit.
    ResponseTooLarge {
        /// Observed cumulative body size that tripped the limit.
        actual: usize,
        /// The effective limit that was exceeded.
        limit: usize,
    },
}

/// Typed detail for a response that exceeded its configured size ceiling.
///
/// Carried across the executor's public boundary so a caller can classify an
/// oversized response and map it to its own status (for example HTTP 413)
/// instead of the opaque gateway response [`run`](FilteredSubrequestExecutor::run)
/// synthesizes.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) struct ResponseTooLargeInfo {
    /// Observed size that tripped the limit, when known.
    pub(crate) actual: Option<usize>,
    /// The effective limit that was exceeded.
    pub(crate) limit: usize,
}

/// Owned downstream request attributes carried into a filtered sub-request.
///
/// A chain-binding callout builds this from its request context so the nested
/// pipeline sees the real client identity, transport security, and request
/// clock — the inputs security and observability filters in an outbound chain
/// depend on.
#[derive(Clone)]
pub struct SubrequestRuntime {
    /// Original downstream client address.
    pub(crate) client_addr: Option<std::net::IpAddr>,
    /// Whether the original downstream uses TLS.
    pub(crate) downstream_tls: bool,
    /// Verified downstream peer identity.
    pub(crate) peer_identity: Option<Arc<praxis_tls::TlsPeerIdentity>>,
    /// Start time of the logical client request.
    pub(crate) request_start: Instant,
}

impl SubrequestRuntime {
    /// Capture the downstream attributes to forward into a filtered sub-request.
    ///
    /// `client_addr`, `downstream_tls`, and `peer_identity` come from the
    /// originating client connection; `request_start` is the instant the logical
    /// client request began, used for consistent duration accounting across the
    /// sub-request.
    #[must_use]
    pub fn new(
        client_addr: Option<std::net::IpAddr>,
        downstream_tls: bool,
        peer_identity: Option<Arc<praxis_tls::TlsPeerIdentity>>,
        request_start: Instant,
    ) -> Self {
        Self {
            client_addr,
            downstream_tls,
            peer_identity,
            request_start,
        }
    }
}

/// A captured sub-response together with its origin classification.
pub(crate) struct SubrequestOutcome {
    /// The buffered or header-only response.
    pub(crate) response: SubResponse,
    /// Where the response came from.
    pub(crate) origin: ResponseOrigin,
    /// Transport failure detail, when the response was synthesized.
    pub(crate) transport_error: Option<TransportFailure>,
}

/// Transport/body shape selected by the sub-request's filters.
pub(crate) enum OpenedResponse {
    /// The complete response was collected and filtered.
    Complete(SubrequestOutcome),
    /// Response headers are filtered; body remains pull-based.
    Streaming {
        /// Live upstream response body.
        body: Box<SubResponseBody>,
        /// Header-time transition metadata.
        outcome: SubrequestOutcome,
    },
}

/// One opened sub-request, including state needed for body/completion processing.
pub(crate) struct OpenedSubrequest {
    /// Owned filter lifecycle state.
    pub(crate) continuation: FilteredSubrequestContinuation,
    /// Buffered or pull-based response source.
    pub(crate) kind: OpenedResponse,
}

/// A sub-request error together with the caller extensions it borrowed.
pub(crate) struct FilteredSubrequestError {
    /// Underlying filter or lifecycle error.
    error: FilterError,
    /// Caller-owned extensions recovered from the nested filter context.
    extensions: RequestExtensions,
    /// Typed response-size-overflow detail, when this error is an overflow.
    too_large: Option<ResponseTooLargeInfo>,
}

impl FilteredSubrequestError {
    /// Build an error before a nested filter context exists.
    fn new(error: FilterError, extensions: RequestExtensions) -> Self {
        Self {
            error,
            extensions,
            too_large: None,
        }
    }

    /// Recover caller-owned extensions from a failed nested context.
    ///
    /// Only the executor-owned mechanisms are stripped; caller-injected
    /// extension types remain for the caller to remove before returning them
    /// to the parent request context.
    fn capture(error: FilterError, ctx: &mut crate::HttpFilterContext<'_>) -> Self {
        ctx.extensions.remove::<PendingStreamChunks>();
        ctx.extensions.remove::<RetainedFilterResults>();
        ctx.extensions.remove::<StreamTermination>();
        Self::new(error, std::mem::take(&mut ctx.extensions))
    }

    /// Attach the typed overflow detail carried by a response-size-limit breach.
    #[must_use]
    fn with_too_large(mut self, info: ResponseTooLargeInfo) -> Self {
        self.too_large = Some(info);
        self
    }

    /// The typed overflow detail, when this error is a response-size breach.
    pub(crate) fn too_large(&self) -> Option<ResponseTooLargeInfo> {
        self.too_large
    }

    /// Split the error from the extensions its caller must restore.
    ///
    /// The typed overflow detail is intentionally dropped here: string-based
    /// callers (the iterative request router's `IrrStepRunner`) keep their
    /// existing behavior, while callers that need the classification read it
    /// through [`too_large`](Self::too_large) first.
    pub(crate) fn into_parts(self) -> (FilterError, RequestExtensions) {
        (self.error, self.extensions)
    }
}

/// Internal result before owned continuation state is captured.
enum RawResponse {
    /// Complete buffered or synthetic response.
    Complete(SubrequestOutcome),
    /// Local filter rejection.
    Rejected(Rejection),
    /// Open pull-based upstream response.
    Streaming {
        /// Live upstream response body.
        body: Box<SubResponseBody>,
        /// Header-time transition metadata.
        outcome: SubrequestOutcome,
    },
    /// An executor-side body-limit check tripped after the response transition.
    ///
    /// Carried out of the timed block (rather than returned as an error inline)
    /// so the shared post-processing path attaches the typed overflow detail to
    /// [`FilteredSubrequestError`] uniformly.
    ResponseTooLarge {
        /// Observed body size that tripped the limit.
        actual: usize,
        /// The effective limit that was exceeded.
        limit: usize,
        /// Human-readable message preserved for string-based callers.
        message: &'static str,
    },
}

/// One sub-request to execute against a named step pipeline.
pub(crate) struct FilteredSubrequestInput<'a> {
    /// Pre-built pipeline for this step.
    pub(crate) pipeline: &'a Arc<FilterPipeline>,
    /// The sub-request to dispatch.
    pub(crate) request: &'a SubRequest,
    /// Human-readable step label for tracing and error messages.
    pub(crate) label: &'a str,
    /// Zero-based iteration index for tracing.
    pub(crate) iteration: u32,
    /// Absolute overall deadline shared across the logical request.
    pub(crate) deadline: Instant,
    /// Caller-provided request extensions, moved into the nested context.
    pub(crate) extensions: RequestExtensions,
}

/// The response an outbound chain produced for a callout.
///
/// The outbound chain — not the calling method — decides whether the response
/// is delivered whole or streamed, by whether a filter selects a streaming
/// sub-request response. [`run`](FilteredSubrequestExecutor::run) surfaces that
/// choice so the caller handles each shape explicitly, mirroring the epic's
/// "one buffered or streaming subrequest" contract.
pub enum CalloutResponse {
    /// The complete response, fully filtered through the response-body phase.
    Buffered(SubResponse),
    /// Transition-time headers now, with the body pulled through the outbound
    /// chain's response-body filters as it flows.
    Streaming {
        /// Status and headers after the response-header phase; the body field
        /// is empty because the payload is delivered through `body`.
        response: SubResponse,
        /// Pull-based response body. Each [`next_chunk`] applies the outbound
        /// chain's response-body filters and, after upstream EOF, flushes any
        /// completion output the chain emits before yielding `None`. An
        /// upstream failure the chain did not convert into a valid terminal
        /// sequence surfaces as an error after buffered chunks drain.
        ///
        /// [`next_chunk`]: crate::StreamingResponseBody::next_chunk
        body: Box<dyn crate::StreamingResponseBody>,
    },
}

/// The classified outcome of a callout run.
///
/// Additive companion to [`CalloutResponse`], returned by
/// [`run_classified`](FilteredSubrequestExecutor::run_classified). It preserves
/// the typed response-size-overflow classification that
/// [`run`](FilteredSubrequestExecutor::run) collapses into a generic gateway
/// response, so a caller can map an oversized response to its own status (for
/// example HTTP 413) instead of an opaque 502. The overflow classification is
/// exposed directly — never inferred from a `502` status.
///
/// Marked `#[non_exhaustive]` so future classified outcomes can be added
/// without breaking downstream `match` arms.
#[non_exhaustive]
pub enum CalloutOutcome {
    /// The outbound chain produced a response — buffered or streaming.
    Response(CalloutResponse),
    /// The response exceeded the configured size limit before delivery.
    ///
    /// Covers both a transport-level overflow (the upstream body exceeded the
    /// per-response ceiling mid-download) and an executor-side body-limit breach
    /// (a response-body filter grew the body past the ceiling). The
    /// response-filter lifecycle runs in both cases before this is surfaced.
    ResponseTooLarge {
        /// Observed size that tripped the limit, when known.
        actual: Option<usize>,
        /// The effective limit that was exceeded.
        limit: usize,
    },
}

/// A pre-resolved upstream a callout stages so the executor dials a specific
/// destination without the outbound chain needing an upstream-selecting filter.
///
/// A chain-binding callout that already knows its destination — for example a
/// provider URL prepared via [`prepare_url_target`] — stages one of these in the
/// request extensions it passes to [`run`](FilteredSubrequestExecutor::run). The
/// executor seeds [`HttpFilterContext::upstream`](crate::HttpFilterContext) from
/// it before the request phase, so the outbound chain carries only cross-cutting
/// filters (observability, security, credentials) and never has to resolve a
/// cluster. Central SSRF, TLS/SNI, and Host enforcement still apply at transport
/// time exactly as for a chain-resolved upstream.
///
/// [`prepare_url_target`]: praxis_core::connectivity::prepare_url_target
pub struct StagedUpstream(pub Upstream);

impl StagedUpstream {
    /// Build a staged upstream from a [`PreparedTarget`].
    ///
    /// The transport address is pinned to the first address the target resolved
    /// (so the executor dials the same endpoint the SSRF validation hook saw,
    /// closing the resolve-then-dial race), the HTTP `Host` authority is the
    /// URL's authority, and TLS/SNI are derived from the URL scheme and host.
    ///
    /// # Errors
    ///
    /// Returns [`FilterError`] if the target resolved no addresses or its TLS
    /// material cannot be prepared.
    pub fn from_prepared_target(target: &PreparedTarget) -> Result<Self, FilterError> {
        let address = target
            .addresses()
            .first()
            .ok_or_else(|| -> FilterError { "filtered_subrequest: prepared target resolved no addresses".into() })?;
        let tls = if target.is_tls() {
            let cluster_tls = ClusterTls {
                sni: Some(target.sni().to_owned()),
                ..ClusterTls::default()
            };
            Some(
                CachedClusterTls::try_from_config(&cluster_tls)
                    .map_err(|error| -> FilterError { format!("filtered_subrequest: invalid TLS: {error}").into() })?,
            )
        } else {
            None
        };
        Ok(Self(Upstream {
            address: Arc::from(address.to_string().as_str()),
            authority: Some(target.host_authority().clone()),
            connection: Arc::new(ConnectionOptions::default()),
            tls,
        }))
    }
}

/// Caller-staged multi-address fallback set for a [`StagedUpstream`].
///
/// [`StagedUpstream`] pins the sub-request's primary transport address (the
/// first address its [`PreparedTarget`] resolved), which closes the
/// resolve-then-dial SSRF race. When a hostname resolved to several addresses,
/// staging this alongside it lets the executor advance past a connection
/// refusal to the next validated address — preserving the DNS fallback the
/// low-level transport performs — without ever re-resolving DNS. Every address
/// was SSRF-validated together by the same preparation hook, and each literal
/// is re-checked at connect time, so dialing any of them is safe. Absent this
/// extension (or with a single address), the executor dials the single staged
/// upstream exactly as before.
pub struct StagedUpstreamFallback(Vec<SocketAddr>);

impl StagedUpstreamFallback {
    /// Capture every address a [`PreparedTarget`] resolved, in resolver order.
    #[must_use]
    pub fn from_prepared_target(target: &PreparedTarget) -> Self {
        Self(target.addresses().to_vec())
    }

    /// The validated fallback addresses, in resolver order.
    #[must_use]
    pub fn addresses(&self) -> &[SocketAddr] {
        &self.0
    }
}

/// No-op retained-state accounting for callers that keep no cross-sub-request
/// state, so the callout entry point never has to expose the
/// [`RetainedStateAccounting`] hook.
struct NoRetainedState;

impl RetainedStateAccounting for NoRetainedState {
    fn exceeds_limit(&self, _extensions: &RequestExtensions) -> bool {
        false
    }
}

/// Executes exactly one filtered sub-request and returns owned continuation state.
pub struct FilteredSubrequestExecutor {
    /// Caller-supplied retained-state ceiling accounting.
    accounting: Box<dyn RetainedStateAccounting + Send + Sync>,
    /// Shared transport client.
    client: praxis_core::subrequest::SubRequestClient,
    /// Nested depth forwarded to sub-requests.
    depth: u8,
    /// Owned downstream request attributes.
    downstream: SubrequestRuntime,
    /// Per-step buffered response ceiling.
    max_response_bytes: usize,
    /// Retained-state raw byte ceiling for stream chunk emission.
    max_state_bytes: usize,
    /// Per-step duration ceiling.
    step_timeout: Duration,
}

impl FilteredSubrequestExecutor {
    /// Build an executor for one logical filtered-sub-request sequence.
    #[expect(
        clippy::too_many_arguments,
        reason = "executor owns explicit subrequest limits and resources"
    )]
    pub(crate) fn new(
        accounting: Box<dyn RetainedStateAccounting + Send + Sync>,
        client: praxis_core::subrequest::SubRequestClient,
        depth: u8,
        downstream: SubrequestRuntime,
        max_response_bytes: usize,
        max_state_bytes: usize,
        step_timeout: Duration,
    ) -> Self {
        Self {
            accounting,
            client,
            depth,
            downstream,
            max_response_bytes,
            max_state_bytes,
            step_timeout,
        }
    }

    /// Build an executor for an application callout that runs a single bound
    /// outbound chain and keeps no cross-sub-request retained state.
    ///
    /// This is the small constructor a chain-binding filter (for example an AI
    /// provider callout) uses together with [`run`]. `client` is the
    /// shared sub-request transport (available from
    /// `HttpFilterContext::subrequest_client`); `downstream` carries the
    /// originating client attributes; `depth` is the current sub-request nesting
    /// depth; `max_response_bytes` caps the response (the buffered body, or the
    /// cumulative bytes emitted by a streaming body); `step_timeout` bounds the
    /// sub-request's own duration within the caller's deadline.
    ///
    /// [`run`]: Self::run
    #[must_use]
    pub fn for_callout(
        client: praxis_core::subrequest::SubRequestClient,
        downstream: SubrequestRuntime,
        depth: u8,
        max_response_bytes: usize,
        step_timeout: Duration,
    ) -> Self {
        // A callout retains no state across sub-requests, so the response ceiling
        // doubles as the stream-chunk emission ceiling.
        Self::new(
            Box::new(NoRetainedState),
            client,
            depth,
            downstream,
            max_response_bytes,
            max_response_bytes,
            step_timeout,
        )
    }

    /// Run `request` through `pipeline` as a filtered sub-request and return the
    /// response the outbound chain produced — buffered or streaming.
    ///
    /// This is the deliberately small entry point for application callout
    /// filters that bound an outbound chain via
    /// [`ChainBindingContext::bind_chain`]. It runs the request, request-body,
    /// response, and (for buffered responses) response-body phases; enforces the
    /// resolved destination authority, DNS/SSRF, TLS/SNI, Host, deadline, and
    /// transport limits; and materializes any staged [`PendingCredentials`] only
    /// after the destination is resolved. `extensions` is the caller-staged
    /// projection moved into the isolated child context.
    ///
    /// The outbound chain decides the response shape: a filter that selects a
    /// streaming sub-request response yields [`CalloutResponse::Streaming`] with
    /// the transition-time headers and a pull-based body that keeps applying the
    /// chain's response-body filters as chunks flow; otherwise the fully
    /// filtered response is returned as [`CalloutResponse::Buffered`].
    ///
    /// # Errors
    ///
    /// Returns [`FilterError`] if a filter phase errors or the deadline is
    /// exceeded before the response transition. For a streaming response, errors
    /// that occur while pulling the body surface from
    /// [`StreamingResponseBody::next_chunk`](crate::StreamingResponseBody::next_chunk)
    /// instead.
    ///
    /// # Examples
    ///
    /// A callout drives its prebuilt outbound chain to a response. In production
    /// the pipeline comes from [`ChainBindingContext::bind_chain`] at
    /// construction and the shared client from the filter's
    /// [`HttpFilterContext`]; here both are built directly so the example runs,
    /// and a `static_response` filter answers locally so no upstream is needed.
    ///
    /// ```
    /// use std::{
    ///     sync::Arc,
    ///     time::{Duration, Instant},
    /// };
    ///
    /// use praxis_core::subrequest::{SubRequestClient, SubRequestConnector};
    /// use praxis_filter::{
    ///     CalloutResponse, FilterEntry, FilterPipeline, FilterRegistry, FilteredSubrequestExecutor,
    ///     RequestExtensions, SubRequest, SubrequestRuntime,
    /// };
    ///
    /// let rt = tokio::runtime::Builder::new_current_thread()
    ///     .enable_all()
    ///     .build()
    ///     .unwrap();
    /// rt.block_on(async {
    ///     // The outbound chain a callout binds once at construction.
    ///     let registry = FilterRegistry::with_builtins();
    ///     let mut chain: Vec<FilterEntry> = serde_yaml::from_str(
    ///         "- filter: static_response\n  status: 200\n  body: hello from the outbound chain\n",
    ///     )
    ///     .unwrap();
    ///     let outbound = Arc::new(FilterPipeline::build(&mut chain, &registry).unwrap());
    ///
    ///     // At request time the callout builds an executor from the shared client
    ///     // and the downstream attributes it reads off its `HttpFilterContext`.
    ///     let client = SubRequestClient::new(SubRequestConnector::new(1, None));
    ///     let downstream = SubrequestRuntime::new(None, false, None, Instant::now());
    ///     let executor = FilteredSubrequestExecutor::for_callout(
    ///         client,
    ///         downstream,
    ///         0,                      // sub-request nesting depth
    ///         1 << 20,                // 1 MiB response ceiling
    ///         Duration::from_secs(5), // per-sub-request step timeout
    ///     );
    ///
    ///     let request = SubRequest {
    ///         method: http::Method::GET,
    ///         uri: http::Uri::from_static("/"),
    ///         headers: http::HeaderMap::new(),
    ///         body: bytes::Bytes::new(),
    ///     };
    ///     let deadline = Instant::now() + Duration::from_secs(5);
    ///     let response = match executor
    ///         .run(&outbound, &request, RequestExtensions::default(), deadline)
    ///         .await
    ///         .expect("the outbound chain produces a response")
    ///     {
    ///         CalloutResponse::Buffered(response) => response,
    ///         CalloutResponse::Streaming { .. } => unreachable!("static_response is buffered"),
    ///     };
    ///
    ///     assert_eq!(response.status, 200);
    ///     assert_eq!(&response.body[..], b"hello from the outbound chain");
    /// });
    /// ```
    ///
    /// [`ChainBindingContext::bind_chain`]: crate::ChainBindingContext::bind_chain
    /// [`HttpFilterContext`]: crate::HttpFilterContext
    #[expect(clippy::large_futures, reason = "delegates to the full step future")]
    #[expect(
        clippy::large_stack_frames,
        reason = "delegates to execute, which reconstructs a full filter context"
    )]
    pub async fn run(
        &self,
        pipeline: &Arc<FilterPipeline>,
        request: &SubRequest,
        extensions: RequestExtensions,
        deadline: Instant,
    ) -> Result<CalloutResponse, FilterError> {
        let input = FilteredSubrequestInput {
            pipeline,
            request,
            label: "callout",
            iteration: 0,
            deadline,
            extensions,
        };
        let opened = self.execute(input).await.map_err(|error| error.into_parts().0)?;
        Ok(self.callout_response_from(opened))
    }

    /// Run `request` through `pipeline` and return a *classified* outcome.
    ///
    /// Additive companion to [`run`](Self::run) for callers that must
    /// distinguish an oversized response from other results. It behaves exactly
    /// like `run` for every response the outbound chain produces, but instead of
    /// collapsing a response-size overflow into a synthesized gateway response it
    /// returns [`CalloutOutcome::ResponseTooLarge`] carrying the observed size
    /// (when known) and the tripped limit. Both the transport-level overflow
    /// (upstream body over the per-response ceiling) and the executor-side
    /// body-limit breach (a response-body filter grew the body past the ceiling)
    /// are covered, and the response-filter lifecycle runs in both cases.
    ///
    /// A genuine upstream `502` is delivered as
    /// [`CalloutOutcome::Response`] — overflow is never inferred from status.
    ///
    /// # Errors
    ///
    /// Returns [`FilterError`] under the same conditions as [`run`](Self::run),
    /// except that a response-size overflow is reported as
    /// [`CalloutOutcome::ResponseTooLarge`] rather than an error.
    ///
    /// # Examples
    ///
    /// Like [`run`](Self::run), but the caller matches a [`CalloutOutcome`].
    /// Because the enum is `#[non_exhaustive]` a wildcard arm is required — here
    /// it also absorbs the streaming response shape. As in the `run` example the
    /// pipeline and client are built directly and a `static_response` filter
    /// answers locally, so the example runs without an upstream.
    ///
    /// ```
    /// use std::{
    ///     sync::Arc,
    ///     time::{Duration, Instant},
    /// };
    ///
    /// use praxis_core::subrequest::{SubRequestClient, SubRequestConnector};
    /// use praxis_filter::{
    ///     CalloutOutcome, CalloutResponse, FilterEntry, FilterPipeline, FilterRegistry,
    ///     FilteredSubrequestExecutor, RequestExtensions, SubRequest, SubrequestRuntime,
    /// };
    ///
    /// let rt = tokio::runtime::Builder::new_current_thread()
    ///     .enable_all()
    ///     .build()
    ///     .unwrap();
    /// rt.block_on(async {
    ///     let registry = FilterRegistry::with_builtins();
    ///     let mut chain: Vec<FilterEntry> = serde_yaml::from_str(
    ///         "- filter: static_response\n  status: 200\n  body: hello from the outbound chain\n",
    ///     )
    ///     .unwrap();
    ///     let outbound = Arc::new(FilterPipeline::build(&mut chain, &registry).unwrap());
    ///
    ///     let client = SubRequestClient::new(SubRequestConnector::new(1, None));
    ///     let downstream = SubrequestRuntime::new(None, false, None, Instant::now());
    ///     let executor = FilteredSubrequestExecutor::for_callout(
    ///         client,
    ///         downstream,
    ///         0,                      // sub-request nesting depth
    ///         1 << 20,                // 1 MiB response ceiling
    ///         Duration::from_secs(5), // per-sub-request step timeout
    ///     );
    ///
    ///     let request = SubRequest {
    ///         method: http::Method::GET,
    ///         uri: http::Uri::from_static("/"),
    ///         headers: http::HeaderMap::new(),
    ///         body: bytes::Bytes::new(),
    ///     };
    ///     let deadline = Instant::now() + Duration::from_secs(5);
    ///     match executor
    ///         .run_classified(&outbound, &request, RequestExtensions::default(), deadline)
    ///         .await
    ///         .expect("the outbound chain produces a response")
    ///     {
    ///         CalloutOutcome::Response(CalloutResponse::Buffered(response)) => {
    ///             assert_eq!(response.status, 200);
    ///             assert_eq!(&response.body[..], b"hello from the outbound chain");
    ///         },
    ///         CalloutOutcome::ResponseTooLarge { actual, limit } => {
    ///             unreachable!("within the {limit}-byte ceiling (saw {actual:?})")
    ///         },
    ///         // `CalloutOutcome` is `#[non_exhaustive]`: downstream callers must
    ///         // keep a wildcard arm so added outcomes — and the streaming
    ///         // response shape — stay forward-compatible.
    ///         _ => unreachable!("static_response yields a buffered response"),
    ///     }
    /// });
    /// ```
    #[expect(clippy::large_futures, reason = "delegates to the full step future")]
    #[expect(
        clippy::large_stack_frames,
        reason = "delegates to execute, which reconstructs a full filter context"
    )]
    pub async fn run_classified(
        &self,
        pipeline: &Arc<FilterPipeline>,
        request: &SubRequest,
        extensions: RequestExtensions,
        deadline: Instant,
    ) -> Result<CalloutOutcome, FilterError> {
        let input = FilteredSubrequestInput {
            pipeline,
            request,
            label: "callout",
            iteration: 0,
            deadline,
            extensions,
        };
        match self.execute(input).await {
            Ok(opened) => {
                // A transport-level overflow rides in the completed outcome's
                // transport classification; surface it as the typed outcome
                // rather than the synthesized gateway response `run` returns.
                if let OpenedResponse::Complete(outcome) = &opened.kind
                    && let Some(TransportFailure::ResponseTooLarge { actual, limit }) = outcome.transport_error
                {
                    return Ok(CalloutOutcome::ResponseTooLarge {
                        actual: Some(actual),
                        limit,
                    });
                }
                Ok(CalloutOutcome::Response(self.callout_response_from(opened)))
            },
            // An executor-side body-limit breach carries the typed detail on the
            // error; every other error stays a plain `FilterError`.
            Err(error) => match error.too_large() {
                Some(info) => Ok(CalloutOutcome::ResponseTooLarge {
                    actual: info.actual,
                    limit: info.limit,
                }),
                None => Err(error.into_parts().0),
            },
        }
    }

    /// Map an opened sub-request onto the buffered/streaming callout response,
    /// shared by [`run`](Self::run) and [`run_classified`](Self::run_classified).
    fn callout_response_from(&self, opened: OpenedSubrequest) -> CalloutResponse {
        let OpenedSubrequest { continuation, kind } = opened;
        match kind {
            OpenedResponse::Complete(outcome) => CalloutResponse::Buffered(outcome.response),
            OpenedResponse::Streaming { body, outcome } => CalloutResponse::Streaming {
                response: outcome.response,
                body: Box::new(CalloutStreamingBody::new(
                    FilteredStreamingBody::new(body, continuation),
                    self.max_response_bytes,
                )),
            },
        }
    }

    /// Execute one sub-request under the remaining overall deadline.
    #[expect(
        clippy::too_many_lines,
        reason = "one sub-request owns the complete filter and transport lifecycle"
    )]
    #[expect(clippy::large_futures, reason = "step execution spans filter and transport futures")]
    #[expect(
        clippy::large_stack_frames,
        reason = "step execution reconstructs a full filter context"
    )]
    pub(crate) async fn execute(
        &self,
        input: FilteredSubrequestInput<'_>,
    ) -> Result<OpenedSubrequest, FilteredSubrequestError> {
        let FilteredSubrequestInput {
            pipeline,
            request: current_request,
            label,
            iteration,
            deadline,
            mut extensions,
        } = input;

        let remaining = deadline
            .checked_duration_since(Instant::now())
            .unwrap_or(Duration::ZERO);
        if remaining.is_zero() {
            return Err(FilteredSubrequestError::new(
                "filtered_subrequest: overall deadline exceeded".to_owned().into(),
                extensions,
            ));
        }

        let mut sub_headers = current_request.headers.clone();
        strip_reserved_headers(&mut sub_headers);
        let sub_req = crate::Request {
            method: current_request.method.clone(),
            uri: current_request.uri.clone(),
            headers: sub_headers.clone(),
        };
        let mut routed_req = sub_req.clone();
        let mut response_header = crate::Response {
            headers: HeaderMap::new(),
            status: http::StatusCode::OK,
        };
        let resources = SubrequestRuntimeResources {
            client_addr: self.downstream.client_addr,
            downstream_tls: self.downstream.downstream_tls,
            health_registry: pipeline.health_registry(),
            id_generator: pipeline.id_generator(),
            kv_stores: pipeline.kv_stores(),
            session_stores: pipeline.session_stores(),
            peer_identity: self.downstream.peer_identity.as_ref(),
            request_start: self.downstream.request_start,
            subrequest_client: Some(&self.client),
            time_source: pipeline.time_source(),
        };
        let mut filter_ctx = build_sub_filter_context(pipeline, &sub_req, resources);
        filter_ctx.extensions = std::mem::take(&mut extensions);
        filter_ctx.extensions.insert(RetainedFilterResults::default());
        filter_ctx.enable_stream_chunk_emission(self.max_state_bytes);
        // A callout may stage a pre-resolved upstream (for example a URL prepared
        // via `prepare_url_target`) so the executor dials a specific destination
        // without the outbound chain needing an upstream-selecting filter. Seed it
        // before the request phase so chain filters observe the resolved upstream
        // and the central SSRF/TLS/Host enforcement at `build_peer` still applies.
        //
        // Keep a copy so the destination can be re-pinned after the request phase:
        // a chain filter may observe the seeded upstream but must not be able to
        // retarget a callout that already resolved and validated its destination.
        // Without the re-pin a filter could redirect the dial — and any body-borne
        // credential (e.g. Tavily's key) — to an authority the callout never
        // prepared. `Upstream` is `Arc`-backed, so the clone is a refcount bump.
        let pinned_upstream = filter_ctx.extensions.remove::<StagedUpstream>().map(|staged| staged.0);
        if let Some(upstream) = &pinned_upstream {
            filter_ctx.upstream = Some(upstream.clone());
        }
        // A callout may additionally stage the full validated address set so a
        // connection refusal on the pinned primary address falls back to the
        // next resolved address (matching the low-level transport's DNS
        // behavior) without re-resolving. Every address was SSRF-validated
        // together by the same preparation hook.
        let fallback_addresses = filter_ctx
            .extensions
            .remove::<StagedUpstreamFallback>()
            .map(|fallback| fallback.0)
            .unwrap_or_default();

        let step_budget = remaining.min(self.step_timeout);
        let step_started = Instant::now();
        let step_deadline = step_started.checked_add(step_budget).unwrap_or(deadline);
        let in_transport = Arc::new(AtomicBool::new(false));
        let in_transport_inner = Arc::clone(&in_transport);

        let step_span = tracing::info_span!("filtered_subrequest", step = label, iteration = iteration);

        let timed: Result<Result<RawResponse, FilterError>, tokio::time::error::Elapsed> =
            tokio::time::timeout(step_budget, async {
            let mut request_body = Some(current_request.body.clone());
            if body_exceeds_limit(
                pipeline.body_capabilities().request_body_mode,
                request_body.as_ref().map_or(0, Bytes::len),
            ) {
                return Ok(RawResponse::Rejected(Rejection::status(413)));
            }

            let pre_read_body = matches!(
                pipeline.body_capabilities().request_body_mode,
                crate::BodyMode::StreamBuffer { .. }
            );
            if pre_read_body {
                let action = pipeline
                    .execute_http_request_body(&mut filter_ctx, &mut request_body, true)
                    .await?;
                if let FilterAction::Reject(rejection) = action {
                    return Ok(RawResponse::Rejected(rejection));
                }
                if self.accounting.exceeds_limit(&filter_ctx.extensions) {
                    return Ok(RawResponse::Rejected(Rejection::status(413)));
                }
                apply_pre_read_header_mutations(&mut routed_req.headers, &filter_ctx);
                filter_ctx.extra_request_headers.clear();
                filter_ctx.request_headers_to_remove.clear();
                filter_ctx.request_headers_to_set.clear();
                filter_ctx.pre_read_mutations.clear();
                sub_headers.clone_from(&routed_req.headers);
                filter_ctx.request = &routed_req;
            }

            let action = pipeline.execute_http_request(&mut filter_ctx).await?;
            if let FilterAction::Reject(rejection) = action {
                return Ok(RawResponse::Rejected(rejection));
            }
            if self.accounting.exceeds_limit(&filter_ctx.extensions) {
                return Ok(RawResponse::Rejected(Rejection::status(413)));
            }
            if !pre_read_body {
                let action = pipeline
                    .execute_http_request_body(&mut filter_ctx, &mut request_body, true)
                    .await?;
                if let FilterAction::Reject(rejection) = action {
                    return Ok(RawResponse::Rejected(rejection));
                }
                if self.accounting.exceeds_limit(&filter_ctx.extensions) {
                    return Ok(RawResponse::Rejected(Rejection::status(413)));
                }
            }

            // Re-pin the staged upstream: the request phase may have let a chain
            // filter observe (and try to rewrite) `ctx.upstream`, but a resolved
            // callout must dial only the destination it prepared. Reasserting here
            // overrides any mid-chain rewrite so a staged credential — a header
            // credential, or for a body-authenticated provider the request body
            // itself — can only ever reach the authority it was prepared for.
            if let Some(upstream) = &pinned_upstream {
                filter_ctx.upstream = Some(upstream.clone());
            }
            let upstream = filter_ctx.upstream.as_ref().ok_or_else(|| -> FilterError {
                format!("filtered_subrequest: step '{label}' did not resolve an upstream").into()
            })?;
            let destination_authority = Arc::clone(&upstream.address);
            // The credential-matching key and upstream Host are the *logical*
            // authority the operator configured for this upstream (`authority`
            // override), not the transport endpoint bytes travel to. Derived
            // from trusted config, never the client-influenced Host header.
            let authority_override: Option<Arc<str>> = upstream
                .authority
                .as_ref()
                .and_then(|value| value.to_str().ok())
                .map(Arc::from);
            // Fall back to the transport only when no override is set.
            let logical_authority: Arc<str> = authority_override
                .clone()
                .unwrap_or_else(|| Arc::clone(&destination_authority));
            in_transport_inner.store(true, Ordering::Release);
            // Build one transport peer per validated address so a connection
            // refusal can fall back to the next. With no staged fallback set (or
            // a single address) this is exactly the prior single-peer dial: the
            // seeded upstream address — a pinned literal on the staged path, or a
            // cluster-resolved hostname on the non-staged path — resolved once.
            // Each fallback peer reuses the seeded upstream's authority, TLS, and
            // connection options; only the transport socket address varies.
            let peers = if fallback_addresses.len() > 1 {
                let mut built = Vec::with_capacity(fallback_addresses.len());
                for address in &fallback_addresses {
                    let mut per_address = upstream.clone();
                    per_address.address = Arc::from(address.to_string().as_str());
                    built.push(build_peer(&per_address, pipeline.allow_private_upstreams()).await);
                }
                built
            } else {
                vec![build_peer(upstream, pipeline.allow_private_upstreams()).await]
            };
            apply_request_header_mutations(&mut sub_headers, &filter_ctx);
            // Mirror the normal proxy path (`apply_authority_override`): a
            // configured authority override becomes the upstream Host,
            // replacing any prior step's or caller's Host. Without an override,
            // default the Host to the transport endpoint only when absent.
            match authority_override.as_deref() {
                Some(authority) => set_authority_host(&mut sub_headers, authority)?,
                None => ensure_destination_host(&mut sub_headers, &destination_authority)?,
            }
            sanitize_subrequest_headers(&mut sub_headers);
            // Destination-bound credential injection: only now that the upstream
            // authority is resolved do we materialize staged secrets, and only
            // into a request bound for the authority each credential was issued
            // for. Injecting after sanitization keeps the credential header from
            // being stripped as hop-by-hop/framing.
            if let Some(pending) = filter_ctx.extensions.remove::<PendingCredentials>() {
                let destination = ResolvedDestination {
                    authority: &logical_authority,
                    transport: &destination_authority,
                };
                let injected = pending.inject_authorized(&destination, &mut sub_headers);
                if injected > 0 {
                    // A credential was authorized against `logical_authority`, so
                    // the upstream must see exactly that authority as its Host. Pin
                    // it here — replacing any step- or caller-set Host the
                    // no-override path preserved — so a secret can never be
                    // delivered under a divergent Host to a shared-vhost endpoint.
                    // (With an override the Host already equals `logical_authority`;
                    // this keeps that true.) A staged credential that matched
                    // nothing injects no secret, so it must not retarget the Host —
                    // doing so would silently change virtual-host routing.
                    set_authority_host(&mut sub_headers, &logical_authority)?;
                    tracing::debug!(
                        authority = %logical_authority,
                        transport = %destination_authority,
                        injected,
                        "materialized destination-bound credentials"
                    );
                }
            }
            let request = SubRequest {
                method: current_request.method.clone(),
                uri: filter_ctx.rewritten_path.as_ref().map_or_else(
                    || current_request.uri.clone(),
                    |path| http::Uri::try_from(path.as_str()).unwrap_or_else(|_| current_request.uri.clone()),
                ),
                headers: sub_headers,
                body: request_body.unwrap_or_default(),
            };
            let mut framework_headers = FrameworkHeaders::new();
            framework_headers.set_depth(self.depth + 1);
            let transport_budget = step_budget
                .checked_sub(step_started.elapsed())
                .unwrap_or(Duration::ZERO);
            if transport_budget.is_zero() {
                return Ok(RawResponse::Rejected(Rejection::status(504)));
            }

            match filter_ctx.subrequest_response_mode {
                SubRequestResponseMode::Streaming => {
                    if matches!(
                        pipeline.body_capabilities().response_body_mode,
                        crate::BodyMode::StreamBuffer { .. }
                    ) {
                        return Err(format!(
                            "filtered_subrequest: step '{label}' selected streaming despite a StreamBuffer response mode"
                        )
                        .into());
                    }
                    let limits = StreamLimits {
                        idle_timeout: STREAMING_IDLE_TIMEOUT,
                        // FilteredStreamingBody enforces the original absolute step
                        // deadline so header time cannot be granted twice.
                        max_stream_duration: None,
                        max_total_bytes: streaming_transport_limit(
                            pipeline.body_capabilities().response_body_mode,
                        ),
                    };
                    let mut response =
                        Err(SubRequestError::Connect("filtered_subrequest: no addresses to dial".to_owned()));
                    for peer in &peers {
                        // Recompute the remaining budget before every fallback
                        // attempt so a slow-but-not-refused earlier address cannot
                        // hand each later attempt the full step budget again; the
                        // absolute step deadline bounds all attempts together (the
                        // outer `tokio::time::timeout` is the hard backstop).
                        let attempt_budget = step_deadline
                            .checked_duration_since(Instant::now())
                            .unwrap_or(Duration::ZERO);
                        if attempt_budget.is_zero() {
                            break;
                        }
                        response = match peer {
                            Ok(peer) => self
                                .client
                                .send_streaming(peer, &request, attempt_budget, limits.clone(), Some(&framework_headers))
                                .await,
                            Err(error) => Err(SubRequestError::Connect(error.to_string())),
                        };
                        // Advance to the next validated address only on a
                        // connection refusal; any other outcome (a response, or a
                        // substantive transport error) is final.
                        if matches!(response, Err(SubRequestError::Connect(_))) {
                            continue;
                        }
                        break;
                    }
                    in_transport_inner.store(false, Ordering::Release);
                    match response {
                        Ok(response) => {
                            let status = response.status;
                            let mut headers = response.headers;
                            sanitize_subresponse_headers(&mut headers);
                            response_header.status = http::StatusCode::from_u16(status)
                                .map_err(|error| -> FilterError { format!("invalid upstream status: {error}").into() })?;
                            response_header.headers.clone_from(&headers);
                            filter_ctx.response_header = Some(&mut response_header);
                            let response_action = pipeline.execute_http_response(&mut filter_ctx).await?;
                            if let FilterAction::Reject(rejection) = response_action {
                                response.body.cancel().await;
                                return Ok(RawResponse::Rejected(rejection));
                            }
                            if self.accounting.exceeds_limit(&filter_ctx.extensions) {
                                response.body.cancel().await;
                                return Ok(RawResponse::Rejected(Rejection::status(413)));
                            }
                            let metadata = filter_ctx.response_header.as_deref().ok_or_else(|| -> FilterError {
                                "filtered_subrequest: response metadata missing after header filters"
                                    .to_owned()
                                    .into()
                            })?;
                            let status = metadata.status;
                            let mut headers = metadata.headers.clone();
                            sanitize_subresponse_headers(&mut headers);
                            Ok(RawResponse::Streaming {
                                body: Box::new(response.body),
                                outcome: SubrequestOutcome {
                                    response: SubResponse { status: status.as_u16(), headers, body: Bytes::new() },
                                    origin: ResponseOrigin::Upstream,
                                    transport_error: None,
                                },
                            })
                        },
                        Err(error) => {
                            let (status, kind) = classify_transport_failure(&error);
                            warn!(step = label, %error, status, "filtered sub-request streaming transport failure");
                            let response = SubResponse { status, headers: HeaderMap::new(), body: Bytes::new() };
                            response_header.status = http::StatusCode::from_u16(status)
                                .map_err(|source| -> FilterError { source.into() })?;
                            filter_ctx.response_header = Some(&mut response_header);
                            let response_action = pipeline.execute_http_response(&mut filter_ctx).await?;
                            if let FilterAction::Reject(rejection) = response_action {
                                return Ok(RawResponse::Rejected(rejection));
                            }
                            if self.accounting.exceeds_limit(&filter_ctx.extensions) {
                                return Ok(RawResponse::Rejected(Rejection::status(413)));
                            }
                            let metadata = filter_ctx.response_header.as_deref().ok_or_else(|| -> FilterError {
                                "filtered_subrequest: response metadata missing after header filters"
                                    .to_owned()
                                    .into()
                            })?;
                            let mut headers = metadata.headers.clone();
                            sanitize_subresponse_headers(&mut headers);
                            Ok(RawResponse::Complete(SubrequestOutcome {
                                response: SubResponse {
                                    status: metadata.status.as_u16(),
                                    headers,
                                    body: response.body,
                                },
                                origin: ResponseOrigin::Transport,
                                transport_error: Some(kind),
                            }))
                        },
                    }
                },
                SubRequestResponseMode::Buffered => {
                    let mut attempt = None;
                    for peer in &peers {
                        // Recompute the remaining budget before every fallback
                        // attempt (see the streaming arm). If the step deadline is
                        // already reached, stop dialing and fall through to the
                        // `attempt.unwrap_or_else(...)` synthesized failure below.
                        let attempt_budget = step_deadline
                            .checked_duration_since(Instant::now())
                            .unwrap_or(Duration::ZERO);
                        if attempt_budget.is_zero() {
                            break;
                        }
                        let outcome = match peer {
                            Ok(peer) => match self
                                .client
                                .execute(peer, &request, self.max_response_bytes, attempt_budget, Some(&framework_headers))
                                .await
                            {
                                Ok(response) => (response, ResponseOrigin::Upstream, None),
                                Err(error) => {
                                    let (status, kind) = classify_transport_failure(&error);
                                    warn!(step = label, %error, status, "filtered sub-request buffered transport failure");
                                    let response =
                                        SubResponse { status, headers: HeaderMap::new(), body: Bytes::new() };
                                    if matches!(error, SubRequestError::Connect(_)) {
                                        // Connection refused/unreachable: remember
                                        // it and try the next validated address.
                                        attempt = Some((response, ResponseOrigin::Transport, Some(kind)));
                                        continue;
                                    }
                                    (response, ResponseOrigin::Transport, Some(kind))
                                },
                            },
                            Err(error) => {
                                warn!(step = label, %error, status = 502_u16, "filtered sub-request buffered transport failure");
                                // Peer construction failed (resolution/SSRF):
                                // remember it and try the next validated address.
                                attempt = Some((
                                    SubResponse { status: 502, headers: HeaderMap::new(), body: Bytes::new() },
                                    ResponseOrigin::Transport,
                                    Some(TransportFailure::Connect),
                                ));
                                continue;
                            },
                        };
                        attempt = Some(outcome);
                        break;
                    }
                    let (mut response, origin, transport_error) = attempt.unwrap_or_else(|| {
                        (
                            SubResponse { status: 502, headers: HeaderMap::new(), body: Bytes::new() },
                            ResponseOrigin::Transport,
                            Some(TransportFailure::Connect),
                        )
                    });
                    in_transport_inner.store(false, Ordering::Release);
                    sanitize_subresponse_headers(&mut response.headers);
                    response_header.status = http::StatusCode::from_u16(response.status)
                        .map_err(|error| -> FilterError { error.into() })?;
                    response_header.headers.clone_from(&response.headers);
                    filter_ctx.response_header = Some(&mut response_header);
                    let response_action = pipeline.execute_http_response(&mut filter_ctx).await?;
                    if let FilterAction::Reject(rejection) = response_action {
                        return Ok(RawResponse::Rejected(rejection));
                    }
                    if self.accounting.exceeds_limit(&filter_ctx.extensions) {
                        return Ok(RawResponse::Rejected(Rejection::status(413)));
                    }
                    let mut body = Some(std::mem::take(&mut response.body));
                    if let Some(limit) = response_body_overflow_limit(
                        pipeline.body_capabilities().response_body_mode,
                        self.max_response_bytes,
                        body.as_ref().map_or(0, Bytes::len),
                    ) {
                        return Ok(RawResponse::ResponseTooLarge {
                            actual: body.as_ref().map_or(0, Bytes::len),
                            limit,
                            message: "filtered_subrequest: step response exceeds configured body limit",
                        });
                    }
                    let body_action = pipeline.execute_http_response_body(&mut filter_ctx, &mut body, true)?;
                    if let FilterAction::Reject(rejection) = body_action {
                        return Ok(RawResponse::Rejected(rejection));
                    }
                    if self.accounting.exceeds_limit(&filter_ctx.extensions) {
                        return Ok(RawResponse::Rejected(Rejection::status(413)));
                    }
                    if let Some(limit) = response_body_overflow_limit(
                        pipeline.body_capabilities().response_body_mode,
                        self.max_response_bytes,
                        body.as_ref().map_or(0, Bytes::len),
                    ) {
                        return Ok(RawResponse::ResponseTooLarge {
                            actual: body.as_ref().map_or(0, Bytes::len),
                            limit,
                            message: "filtered_subrequest: transformed step response exceeds configured body limit",
                        });
                    }
                    response.body = body.unwrap_or_default();
                    if let Some(metadata) = filter_ctx.response_header.as_deref() {
                        response.status = metadata.status.as_u16();
                        response.headers.clone_from(&metadata.headers);
                    }
                    sanitize_subresponse_headers(&mut response.headers);
                    Ok(RawResponse::Complete(SubrequestOutcome { response, origin, transport_error }))
                },
            }
            }
            .instrument(step_span))
            .await;

        let mut raw = match timed {
            Ok(Ok(raw)) => raw,
            Ok(Err(error)) => return Err(FilteredSubrequestError::capture(error, &mut filter_ctx)),
            Err(_) if in_transport.load(Ordering::Acquire) => RawResponse::Complete(SubrequestOutcome {
                response: SubResponse {
                    status: 504,
                    headers: HeaderMap::new(),
                    body: Bytes::new(),
                },
                origin: ResponseOrigin::Transport,
                transport_error: Some(TransportFailure::DeadlineExceeded),
            }),
            Err(_) => RawResponse::Rejected(Rejection::status(504)),
        };

        filter_ctx.response_header = None;
        if filter_ctx.subrequest_response_mode == SubRequestResponseMode::Streaming
            && let RawResponse::Complete(outcome) = &mut raw
            && outcome.origin == ResponseOrigin::Transport
        {
            let cause = outcome
                .transport_error
                .map_or(StreamTerminationCause::Io, stream_termination_cause);
            filter_ctx.extensions.insert(StreamTermination::new(cause));
            let response_snapshot = crate::Response {
                status: http::StatusCode::from_u16(outcome.response.status).unwrap_or(http::StatusCode::BAD_GATEWAY),
                headers: outcome.response.headers.clone(),
            };
            let mut completion_body = None;
            let completion_action = pipeline
                .execute_http_response_body_with_response_header(
                    &mut filter_ctx,
                    &mut completion_body,
                    true,
                    Some(&response_snapshot),
                )
                .map_err(|error| FilteredSubrequestError::capture(error, &mut filter_ctx))?;
            if let FilterAction::Reject(_) = completion_action {
                let error = "filtered_subrequest: step completion filter rejected an abnormal stream"
                    .to_owned()
                    .into();
                return Err(FilteredSubrequestError::capture(error, &mut filter_ctx));
            }
            if self.accounting.exceeds_limit(&filter_ctx.extensions) {
                let error = "filtered_subrequest: retained state limit exceeded during stream completion"
                    .to_owned()
                    .into();
                return Err(FilteredSubrequestError::capture(error, &mut filter_ctx));
            }
            // Mirror the two buffered overflow sites: the effective ceiling is the
            // smaller of `max_response_bytes` and the pipeline's response body mode.
            //
            // Reachability invariant — today this collapses to `max_response_bytes`.
            // A `StreamBuffer` response mode is rejected before streaming is selected
            // (the guard at the top of the streaming arm), and a `SizeLimit` mode only
            // arises when no response-body filter runs — in which case nothing writes
            // `completion_body` and it stays empty. So the only mode under which a
            // completion body can exist is `Stream`, for which the helper returns
            // exactly `max_response_bytes`. Routing through the shared helper keeps all
            // three sites uniform and correct-by-construction should that guard ever
            // be relaxed to admit a tighter response mode here.
            if let Some(limit) = response_body_overflow_limit(
                pipeline.body_capabilities().response_body_mode,
                self.max_response_bytes,
                completion_body.as_ref().map_or(0, Bytes::len),
            ) {
                let error = FilteredSubrequestError::capture(
                    "filtered_subrequest: abnormal completion exceeds response body limit"
                        .to_owned()
                        .into(),
                    &mut filter_ctx,
                )
                .with_too_large(ResponseTooLargeInfo {
                    actual: Some(completion_body.as_ref().map_or(0, Bytes::len)),
                    limit,
                });
                return Err(error);
            }
            outcome.response.body = completion_body.unwrap_or_default();
        }
        let (kind, response_snapshot, completed) = match raw {
            RawResponse::Complete(outcome) => {
                let snapshot = crate::Response {
                    status: http::StatusCode::from_u16(outcome.response.status)
                        .unwrap_or(http::StatusCode::BAD_GATEWAY),
                    headers: outcome.response.headers.clone(),
                };
                (OpenedResponse::Complete(outcome), snapshot, true)
            },
            RawResponse::Rejected(rejection) => {
                let response = subresponse_from_rejection(rejection);
                let snapshot = crate::Response {
                    status: http::StatusCode::from_u16(response.status).unwrap_or(http::StatusCode::BAD_GATEWAY),
                    headers: response.headers.clone(),
                };
                (
                    OpenedResponse::Complete(SubrequestOutcome {
                        response,
                        origin: ResponseOrigin::Local,
                        transport_error: None,
                    }),
                    snapshot,
                    true,
                )
            },
            RawResponse::Streaming { body, outcome } => {
                let snapshot = crate::Response {
                    status: http::StatusCode::from_u16(outcome.response.status)
                        .unwrap_or(http::StatusCode::BAD_GATEWAY),
                    headers: outcome.response.headers.clone(),
                };
                (OpenedResponse::Streaming { body, outcome }, snapshot, false)
            },
            // An executor-side body-limit breach carries the typed overflow
            // detail out as an error, uniformly with the transport path. The
            // response-filter lifecycle already ran before the breach.
            RawResponse::ResponseTooLarge { actual, limit, message } => {
                let error = FilteredSubrequestError::capture(message.to_owned().into(), &mut filter_ctx)
                    .with_too_large(ResponseTooLargeInfo {
                        actual: Some(actual),
                        limit,
                    });
                return Err(error);
            },
        };
        let request_snapshot = crate::Request {
            method: filter_ctx.request.method.clone(),
            uri: filter_ctx.request.uri.clone(),
            headers: filter_ctx.request.headers.clone(),
        };
        let continuation = FilteredSubrequestContinuation::capture(
            Arc::clone(pipeline),
            request_snapshot,
            response_snapshot,
            &mut filter_ctx,
            completed,
            step_deadline,
        );
        Ok(OpenedSubrequest { continuation, kind })
    }
}