boatramp-server 0.4.4

boatramp HTTP server + API library (streaming static-site publishing)
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
//! GraphQL federation executor: run a query plan and stitch the results.
//!
//! The planner (`graphql_plan`) produces an ordered list of fetches; this executor runs
//! each — a root fetch, or a dependent `_entities` fetch whose representations are built
//! from an earlier fetch's data — and merges every fetch's result into one response,
//! joining entities by their `@key`. Dispatching a fetch to its subgraph is abstracted
//! behind [`SubgraphFetcher`], so the stitching logic is tested with a mock and reused over
//! the real [`BackendRouter`] in the serving path — which routes each fetch to its
//! subgraph's backend (a wasm function, or the SQL data connector), letting a GraphQL→SQL
//! subgraph and a GraphQL→Wasi subgraph compose in one supergraph.
//!
//! Scope is **core federation**: object- and list-valued join points; entities are
//! stitched by representation order (which `_entities` preserves). Nested jumps work via
//! response paths into the already-stitched tree.

use crate::graphql_plan::QueryPlan;
use serde_json::{json, Map, Value};

/// Dispatches one planned fetch to a subgraph and returns its GraphQL response JSON
/// (an object with a `data` field, or a bare data object). `class` is the fetch's tenancy class
/// (R4/D8) — `Own` (today's behavior) or `Target{..}` (read another tenant's public subset); the
/// router binds the corresponding host scope before the subgraph runs.
#[async_trait::async_trait]
pub(crate) trait SubgraphFetcher: Sync {
    async fn fetch(
        &self,
        subgraph: &str,
        query: &str,
        variables: Value,
        class: &boatramp_core::tenancy::TenancyClass,
    ) -> Value;
}

/// Execute `plan` with `fetcher`, returning the merged `{ "data": … }` response. `variables`
/// is the incoming operation's variables (a JSON object, or null) — forwarded to every root
/// fetch so a field argument bound to `$var` resolves; an `_entities` fetch also receives them
/// alongside its `representations`.
pub(crate) async fn execute(
    plan: &QueryPlan,
    fetcher: &dyn SubgraphFetcher,
    variables: &Value,
) -> Value {
    let mut data = json!({});
    let mut errors: Vec<Value> = Vec::new();
    for fetch in &plan.fetches {
        match &fetch.requires {
            None => {
                let resp = fetcher
                    .fetch(
                        &fetch.subgraph,
                        &fetch.query,
                        variables.clone(),
                        &fetch.class,
                    )
                    .await;
                // A root fetch's errors carry their own path relative to the root.
                collect_errors(&mut errors, &resp, &[]);
                if let Some(d) = fetch_data(&resp) {
                    merge(&mut data, d);
                }
            }
            Some(req) => {
                // Build the entity representations from the already-stitched tree at the
                // provider's response path, run the `_entities` fetch, and stitch the
                // resolved entity fields back in at that path.
                let reprs = representations(&data, &req.path, &req.type_name, &req.key);
                let resp = fetcher
                    .fetch(
                        &fetch.subgraph,
                        &fetch.query,
                        with_representations(variables, reprs),
                        &fetch.class,
                    )
                    .await;
                // An `_entities` fetch's errors are relative to `_entities[i]`; prefix them
                // with the provider path so a client can locate the failing field.
                collect_errors(&mut errors, &resp, &req.path);
                let entities = resp
                    .pointer("/data/_entities")
                    .or_else(|| resp.pointer("/_entities"))
                    .cloned()
                    .unwrap_or_else(|| json!([]));
                stitch(&mut data, &req.path, &entities);
            }
        }
    }
    // Assemble the spec envelope: `errors` is present only when at least one fetch reported
    // one, so a wholly-successful query is byte-identical to before.
    if errors.is_empty() {
        return json!({ "data": data });
    }
    // GraphQL error propagation: when a query fully errors so that **nothing** resolved (every
    // contributing fetch nulled its own data or errored, leaving `data` an empty object), the
    // response `data` is `null`, not `{}` — a fully-errored non-nullable root field nulls the
    // whole `data`. A *partial* success (some field resolved, or a nullable field arrived as
    // `{field: null}`) leaves `data` non-empty and is preserved.
    let data = match &data {
        Value::Object(map) if map.is_empty() => Value::Null,
        _ => data,
    };
    json!({ "data": data, "errors": errors })
}

/// The data of a fetch response's `{ "data": … }` envelope to merge into the composed tree,
/// or `None` when there is nothing to merge. An **error-only** response (the infra-failure
/// paths in this file build `{ "errors": [...] }` with no `data`) and an explicit top-level
/// `{ "data": null }` (a subgraph's non-null field failed) both contribute no data — so a
/// failing subgraph never wipes the other subgraphs' data, and its `{"errors":…}` object is
/// never itself merged in as data. A response with neither key is treated as envelope-less
/// raw data (the lenient path some mocks use).
fn fetch_data(resp: &Value) -> Option<&Value> {
    match resp.get("data") {
        Some(Value::Null) => None,
        Some(d) => Some(d),
        None if resp.get("errors").is_some() => None,
        None => Some(resp),
    }
}

/// Accumulate a fetch response's `errors` into `acc`, prefixing each error's `path` with
/// `base_path` (the fetch's response path — empty for a root fetch, the provider path for an
/// `_entities`/`requires` fetch). `message`, `extensions`, and `locations` are forwarded
/// verbatim. An absent / empty / non-array `errors` contributes nothing, so a legitimately
/// null field with no error stays error-free.
fn collect_errors(acc: &mut Vec<Value>, resp: &Value, base_path: &[String]) {
    let Some(errs) = resp.get("errors").and_then(Value::as_array) else {
        return;
    };
    for err in errs {
        let mut err = err.clone();
        if !base_path.is_empty() {
            let suffix = err
                .get("path")
                .and_then(Value::as_array)
                .cloned()
                .unwrap_or_default();
            let mut full: Vec<Value> = base_path.iter().map(|s| Value::String(s.clone())).collect();
            full.extend(suffix);
            if let Value::Object(m) = &mut err {
                m.insert("path".to_string(), Value::Array(full));
            }
        }
        acc.push(err);
    }
}

/// The variables for an `_entities` fetch: the incoming operation variables (when a JSON object)
/// plus the computed `representations` the `_entities(representations: $representations)` binds.
fn with_representations(variables: &Value, reprs: Value) -> Value {
    let mut map = match variables {
        Value::Object(m) => m.clone(),
        _ => serde_json::Map::new(),
    };
    map.insert("representations".to_string(), reprs);
    Value::Object(map)
}

/// Dispatch one fetch to a subgraph **function** over the in-process invoke path (no network
/// hop, no SSRF surface) — the subgraph name is the function name — mapping the result (or a
/// precise error) to a GraphQL response. An external gateway request is the root of the call
/// chain (`depth` 0); a **guest-initiated** run (via the `graphql` capability) dispatches at the
/// guest's own depth so its sub-fetches count against the shared call-depth cap. Used by the
/// [`BackendRouter`]'s function branch.
///
/// The caller's verified `bearer` is forwarded as the `Authorization` header so a subgraph
/// that authorizes per field sees the same principal on **every** fetch — a root fetch and a
/// dependent `_entities` hydration alike. Without it a subgraph's non-`public` field would see
/// an anonymous caller and refuse. `bearer` is the raw token (the gateway already stripped the
/// `Bearer ` scheme), so re-add it.
async fn invoke_subgraph(
    invoker: &dyn boatramp_handlers::Invoker,
    subgraph: &str,
    query: &str,
    variables: Value,
    bearer: Option<&str>,
    depth: u32,
) -> Value {
    let body = json!({ "query": query, "variables": variables })
        .to_string()
        .into_bytes();
    let mut headers = vec![("content-type".to_string(), b"application/json".to_vec())];
    if let Some(token) = bearer {
        headers.push((
            "authorization".to_string(),
            format!("Bearer {token}").into_bytes(),
        ));
    }
    let request = boatramp_handlers::InvokeRequest {
        method: "POST".to_string(),
        path: "/".to_string(),
        headers,
        body,
    };
    match invoker.invoke(subgraph, request, depth).await {
        Ok(resp) => serde_json::from_slice(&resp.body).unwrap_or_else(|_| {
            json!({ "errors": [{ "message": format!("subgraph `{subgraph}` returned invalid JSON") }] })
        }),
        // A registered subgraph with no deployed function of the same name — the registry
        // SDL and the actual subgraph function are decoupled, so surface this precisely
        // rather than as a generic outage (a silently-wrong result would be worse).
        Err(boatramp_handlers::InvokeError::NotFound) => json!({ "errors": [{
            "message": format!(
                "subgraph `{subgraph}` is registered but no function named `{subgraph}` is deployed"
            )
        }] }),
        Err(boatramp_handlers::InvokeError::Failed(msg)) => json!({ "errors": [{
            "message": format!("subgraph `{subgraph}` failed: {msg}")
        }] }),
    }
}

/// Build the request's target-tenant read scope (R4/D8) from the project [`TenancySchema`] and a
/// host-resolved target tenant `B`: for every table that declares a public subset **and** resolves
/// to a tenant column, bind `tenant_column = B` + that table's public predicate (lowered to GDC
/// terms). A table with a public subset but no resolvable tenant column is omitted — so a target
/// read of it is refused (deny-by-default). `B` is host-derived at the edge (terminating domain /
/// verified capability / handle lookup), NEVER guest input.
pub(crate) fn build_target_scope(
    schema: &boatramp_core::tenancy::TenancySchema,
    tenant_value: boatramp_core::sql::SqlValue,
) -> crate::graphql_data::policy::TargetScope {
    use crate::graphql_data::policy::{TargetScope, TargetTable};
    use boatramp_core::tenancy::ResolvedScope;
    let mut tables = std::collections::BTreeMap::new();
    for (table, subset) in &schema.public_subsets {
        // Only a table with a resolvable tenant column is target-readable; anything else is left
        // out of the map, so the GDC refuses a target read of it (deny-by-default).
        let Some(ResolvedScope::Column(tenant_column)) = schema.resolve(table) else {
            continue;
        };
        let public = lower_public_terms_gdc(&subset.predicate);
        // Load-time fail-closed (defense-in-depth, matching the deny-all-on-unreadable-schema
        // contract): an EMPTY public predicate would confine only to `tenant = B` — a match-all over
        // B's rows including its private ones. `set_project_tenancy::validate` already rejects this
        // at the write path; here we ALSO omit such a table (⇒ a target read of it is refused
        // deny-by-default) so a schema authored on an older binary can never leak at read time.
        if public.is_empty() {
            continue;
        }
        tables.insert(
            table.clone(),
            TargetTable {
                tenant_column,
                public,
            },
        );
    }
    TargetScope {
        tenant_value,
        tables,
    }
}

/// The names of `query`'s root fields that resolve to a **target** tenancy class (R4/D8) — the
/// fields whose eligibility the operator's `target_eligible_fields` allowlist gates. Empty when the
/// query has no target root field (or doesn't parse — the planner already validated it). Used at
/// the gateway to refuse, fresh per request, a target field the project hasn't opted in.
pub(crate) fn target_root_fields(
    query: &str,
    sg: &crate::graphql_federation::Supergraph,
) -> Vec<String> {
    use async_graphql_parser::types::{DocumentOperations, Selection};
    let Ok(doc) = async_graphql_parser::parse_query(query) else {
        return Vec::new();
    };
    let op = match &doc.operations {
        DocumentOperations::Single(op) => &op.node,
        DocumentOperations::Multiple(m) => match m.values().next() {
            Some(o) => &o.node,
            None => return Vec::new(),
        },
    };
    op.selection_set
        .node
        .items
        .iter()
        .filter_map(|s| match &s.node {
            Selection::Field(f) => {
                let name = f.node.name.node.as_str();
                sg.root_tenancy
                    .get(name)
                    .filter(|c| c.is_target())
                    .map(|_| name.to_string())
            }
            _ => None,
        })
        .collect()
}

/// Lower a host-held [`PublicPredicate`](boatramp_core::tenancy::PublicPredicate) into GDC
/// [`ResolvedTerm`](crate::graphql_data::policy::ResolvedTerm)s (literals become bound values, never
/// interpolated). The GDC analogue of `boatramp_core::orm::lower_public_terms`.
fn lower_public_terms_gdc(
    pred: &boatramp_core::tenancy::PublicPredicate,
) -> Vec<crate::graphql_data::policy::ResolvedTerm> {
    use crate::graphql_data::policy::{ResolvedTerm, RowOp};
    use boatramp_core::sql::SqlValue;
    use boatramp_core::tenancy::{PublicCmp, PublicLiteral, PublicTerm};
    pred.terms
        .iter()
        .map(|t| match t {
            PublicTerm::Cmp { column, op, value } => ResolvedTerm::Cmp {
                column: column.clone(),
                op: match op {
                    PublicCmp::Eq => RowOp::Eq,
                    PublicCmp::Ne => RowOp::Ne,
                    PublicCmp::Lt => RowOp::Lt,
                    PublicCmp::Le => RowOp::Le,
                    PublicCmp::Gt => RowOp::Gt,
                    PublicCmp::Ge => RowOp::Ge,
                },
                value: match value {
                    PublicLiteral::Bool(b) => SqlValue::Boolean(*b),
                    PublicLiteral::Int(n) => SqlValue::Integer(*n),
                    PublicLiteral::Text(s) => SqlValue::Text(s.clone()),
                },
            },
            PublicTerm::Null { column, negated } => ResolvedTerm::Null {
                column: column.clone(),
                negated: *negated,
            },
        })
        .collect()
}

/// A [`SubgraphFetcher`] that dispatches each fetch to the **right backend**: a SQL-backed
/// subgraph (compiled to SQL against a managed database) or, by default, a wasm function.
/// This is where a GraphQL→SQL subgraph and a GraphQL→Wasi subgraph compose in one
/// supergraph — the gateway plans uniformly and this routes each fetch by its subgraph's
/// registered kind.
pub(crate) struct BackendRouter {
    invoker: std::sync::Arc<dyn boatramp_handlers::Invoker>,
    project: String,
    sql_provider: Option<std::sync::Arc<dyn boatramp_core::sql::SqlBackends>>,
    /// SQL-backed subgraphs: `name → (site, data config)`. A subgraph not here is a function.
    sql_subgraphs: std::collections::BTreeMap<
        String,
        (String, boatramp_core::config::HandlerGraphqlDataConfig),
    >,
    /// The request's verified app bearer token — bound to a SQL subgraph's claim-based
    /// `row_filter`, and forwarded as `Authorization` to a function subgraph so its per-field
    /// authorization sees the same principal.
    bearer: Option<String>,
    /// The call-chain depth at which sub-fetches are invoked. `0` for an external gateway
    /// request (the root); a guest-initiated run sets its own depth so the shared cap counts
    /// its sub-fetches. See [`BackendRouter::at_depth`].
    depth: u32,
    /// The request's host-resolved **target-tenant scope** (R4/D8), if any: read another tenant
    /// `B`'s public subset, confined by the project schema. `Some` only when the edge resolved a
    /// target identity for this request (5a: from the carried domain). A `Target`-class fetch with
    /// no resolved target scope here **fails closed** — a target read never runs un-confined.
    target: Option<crate::graphql_data::policy::TargetScope>,
}

impl BackendRouter {
    pub(crate) fn new(
        invoker: std::sync::Arc<dyn boatramp_handlers::Invoker>,
        project: String,
        sql_provider: Option<std::sync::Arc<dyn boatramp_core::sql::SqlBackends>>,
        sql_subgraphs: std::collections::BTreeMap<
            String,
            (String, boatramp_core::config::HandlerGraphqlDataConfig),
        >,
        bearer: Option<String>,
    ) -> Self {
        Self {
            invoker,
            project,
            sql_provider,
            sql_subgraphs,
            bearer,
            depth: 0,
            target: None,
        }
    }

    /// Dispatch this router's sub-fetches at call-chain `depth` (default `0`, the external
    /// gateway root). A guest-initiated run sets its own depth so the shared invoke depth cap
    /// counts a guest op → subgraph fetch → guest op chain and stops it looping.
    pub(crate) fn at_depth(mut self, depth: u32) -> Self {
        self.depth = depth;
        self
    }

    /// Bind the request's host-resolved target-tenant scope (R4/D8) — used to serve a
    /// `Target`-class fetch (read another tenant `B`'s public subset). Absent ⇒ a `Target` fetch
    /// fails closed. Set by the edge once it has resolved the target identity + built the confinement
    /// from the project schema.
    pub(crate) fn with_target(
        mut self,
        target: Option<crate::graphql_data::policy::TargetScope>,
    ) -> Self {
        self.target = target;
        self
    }

    /// Resolve a fetch for a SQL-backed subgraph: open the site's database, introspect, and
    /// compile + run the fetch (the connector's own path), returning its GraphQL response.
    async fn run_sql(
        &self,
        subgraph: &str,
        site: &str,
        config: &boatramp_core::config::HandlerGraphqlDataConfig,
        query: &str,
        variables: Value,
        target: Option<&crate::graphql_data::policy::TargetScope>,
    ) -> Value {
        let Some(provider) = &self.sql_provider else {
            return json!({ "errors": [{ "message": "the federation gateway has no SQL backend configured" }] });
        };
        let backend = match provider.database(&self.project, site, &config.source).await {
            Ok(backend) => backend,
            Err(err) => {
                return json!({ "errors": [{ "message": format!("subgraph `{subgraph}` database unavailable: {err}") }] })
            }
        };
        let schema = match crate::graphql_data::introspect::introspect_sqlite(backend.as_ref())
            .await
        {
            Ok(schema) => schema,
            Err(err) => {
                return json!({ "errors": [{ "message": format!("subgraph `{subgraph}` introspection failed: {err}") }] })
            }
        };
        let policy = crate::graphql_data::policy_from_config(config);
        let claims =
            crate::graphql_data::request_claims(&self.project, self.bearer.as_deref(), config)
                .await;
        let dialect = crate::graphql_data::dialect::Sqlite;
        let invoker = Some(self.invoker.as_ref());
        // A SQL subgraph resolves both root fetches and — so it's a full federation entity
        // resolver — `_entities` fetches (a keyed SELECT joined back by representation order).
        if crate::graphql_data::compile::is_entities_query(query) {
            crate::graphql_data::runner::execute_entities(
                backend.as_ref(),
                &dialect,
                &schema,
                &policy,
                &claims,
                query,
                &variables,
                invoker,
                self.bearer.as_deref(),
                self.depth,
                target,
            )
            .await
        } else {
            crate::graphql_data::runner::execute(
                backend.as_ref(),
                &dialect,
                &schema,
                &policy,
                &claims,
                query,
                &variables,
                invoker,
                self.bearer.as_deref(),
                self.depth,
                target,
            )
            .await
        }
    }
}

#[async_trait::async_trait]
impl SubgraphFetcher for BackendRouter {
    async fn fetch(
        &self,
        subgraph: &str,
        query: &str,
        variables: Value,
        class: &boatramp_core::tenancy::TenancyClass,
    ) -> Value {
        // Resolve the host scope to bind for this fetch (R4/D8). `Own` ⇒ today's path. `Target` ⇒
        // this request's host-resolved target scope, or **fail closed** if none was resolved — a
        // target read never runs un-confined.
        let target = match class {
            boatramp_core::tenancy::TenancyClass::Own => None,
            boatramp_core::tenancy::TenancyClass::Target { .. } => match &self.target {
                Some(ts) => Some(ts),
                None => {
                    return json!({ "errors": [{ "message":
                        "target-tenant scope was not resolved for this request (fail-closed)" }] })
                }
            },
            // `TenancyClass` is `#[non_exhaustive]`: any future class the host doesn't yet bind a
            // scope for fails closed rather than running under the own (or no) scope.
            _ => {
                return json!({ "errors": [{ "message":
                    "unsupported tenancy class for this fetch (fail-closed)" }] })
            }
        };
        if let Some((site, config)) = self.sql_subgraphs.get(subgraph) {
            return self
                .run_sql(subgraph, site, config, query, variables, target)
                .await;
        }
        // A wasm subgraph carries no target confinement in this stage, so a `Target` fetch to one is
        // refused (target reads are served by SQL/GDC subgraphs). An `Own` wasm fetch is unchanged.
        if class.is_target() {
            return json!({ "errors": [{ "message":
                "target-tenant reads are supported on SQL subgraphs only" }] });
        }
        invoke_subgraph(
            self.invoker.as_ref(),
            subgraph,
            query,
            variables,
            self.bearer.as_deref(),
            self.depth,
        )
        .await
    }
}

/// The server's [`SupergraphRunner`](boatramp_handlers::SupergraphRunner): runs a guest's
/// GraphQL operation against the project's composed supergraph in-process — the same planner +
/// executor an external `/graphql` request uses (via [`BackendRouter`]), plus two guest-specific
/// gates: a **forced safelist** (only pre-registered operations run — deny-by-default) and the
/// **shared depth cap** (sub-fetches dispatch at the guest's own depth so a run → subgraph fetch
/// → run chain cannot loop). The caller's own bearer is forwarded and re-verified per subgraph,
/// so a guest cannot escalate by running this.
pub(crate) struct FederationRunner {
    runtime: std::sync::Weak<crate::HandlerRuntimeInner>,
    project: String,
}

impl FederationRunner {
    /// A runner bound to `runtime`; scope it per request with [`FederationRunner::scoped`].
    pub(crate) fn new(runtime: std::sync::Weak<crate::HandlerRuntimeInner>) -> Self {
        Self {
            runtime,
            project: boatramp_core::project::DEFAULT_PROJECT.to_string(),
        }
    }

    /// A runner scoped to `project` (all registry/plan/execute lookups are project-qualified),
    /// as the guest grant needs — mirrors the invoker's per-tenant scoping.
    pub(crate) fn scoped(
        &self,
        project: boatramp_core::project::ProjectRef<'_>,
    ) -> std::sync::Arc<dyn boatramp_handlers::SupergraphRunner> {
        std::sync::Arc::new(Self {
            runtime: self.runtime.clone(),
            project: project.as_str().to_string(),
        })
    }
}

/// Strip a leading `Bearer ` scheme (case-insensitive) from a forwarded Authorization value,
/// leaving the raw token [`BackendRouter`] expects (it re-adds the scheme per subgraph).
fn strip_bearer(raw: &str) -> &str {
    raw.strip_prefix("Bearer ")
        .or_else(|| raw.strip_prefix("bearer "))
        .unwrap_or(raw)
}

#[async_trait::async_trait]
impl boatramp_handlers::SupergraphRunner for FederationRunner {
    async fn run(
        &self,
        request: boatramp_handlers::GraphqlRequest,
        depth: u32,
    ) -> Result<Vec<u8>, boatramp_handlers::SupergraphRunError> {
        use boatramp_handlers::SupergraphRunError;
        let Some(inner) = self.runtime.upgrade() else {
            return Err(SupergraphRunError::Failed(
                "handler runtime is shutting down".into(),
            ));
        };
        let kv = inner.kv.as_ref();
        let project = self.project.as_str();

        // Deny-by-default operation surface: a guest may run only a pre-registered (safelisted)
        // operation — by its hash for `run-persisted`, or the hash of the supplied `query` for
        // `run`. The subgraph field guards remain the hard enforcement; this is the floor.
        let hash = match (&request.query, &request.persisted_hash) {
            (Some(query), _) => crate::graphql_apq::sha256_hex(query),
            (None, Some(hash)) => hash.clone(),
            (None, None) => {
                return Err(SupergraphRunError::PlanFailed(
                    "no query or persisted hash supplied".into(),
                ))
            }
        };
        let Some(query) = crate::graphql_apq::safelisted_query(kv, project, &hash).await else {
            return Err(SupergraphRunError::NotSafelisted);
        };

        // Query-guard the resolved operation (depth/complexity), exactly as at the edge.
        let limits = crate::graphql_guard::limits_from(
            &boatramp_core::config::HandlerGraphqlConfig::default(),
        );
        if let crate::graphql_guard::GuardVerdict::Reject(reason) =
            crate::graphql_guard::guard_query(&query, &limits)
        {
            return Err(SupergraphRunError::PlanFailed(reason));
        }

        // Compose + plan against the project's registered subgraphs — memoized per project by
        // composition version (and, for the plan, the operation hash `hash`), so an agent turn's
        // N runs don't each re-list, re-parse every SDL, and re-plan a graph that only changes on
        // deploy. Invalidation is the version check inside the cache.
        let cached = inner
            .graphql_cache
            .supergraph(kv, project)
            .await
            .map_err(|e| {
                SupergraphRunError::Failed(format!("supergraph composition failed: {e}"))
            })?;
        let plan = inner
            .graphql_cache
            .plan(project, cached.version, &hash, &query, &cached.supergraph)
            .map_err(|_| SupergraphRunError::PlanFailed("the query cannot be planned".into()))?;

        let Some(invoker) = inner.invoker.get() else {
            return Err(SupergraphRunError::Failed("no invoker configured".into()));
        };
        let sql_subgraphs = (*cached.sql_subgraphs).clone();
        // Forward the guest's own bearer (re-verified per subgraph — no escalation), and dispatch
        // sub-fetches at this run's depth so the shared cap counts them.
        let bearer = request
            .authorization
            .as_deref()
            .map(|raw| strip_bearer(raw).to_string());
        let router = BackendRouter::new(
            // A federated sub-fetch doesn't propagate an in-site tenant (the GDC row policy governs
            // data); a scoped sibling fail-closes for an `own` op.
            invoker.scoped(boatramp_core::project::ProjectRef::new(project), Vec::new()),
            project.to_string(),
            inner.sql.clone(),
            sql_subgraphs,
            bearer,
        )
        .at_depth(depth);
        // The guest's operation variables (a JSON object string) — forwarded to the fetches so a
        // mutation/field argument bound to `$var` resolves. An unparsable/empty value is `{}`.
        let variables: Value =
            serde_json::from_str(&request.variables).unwrap_or_else(|_| json!({}));
        let response = execute(&plan, &router, &variables).await;
        serde_json::to_vec(&response)
            .map_err(|e| SupergraphRunError::Failed(format!("serializing response: {e}")))
    }
}

/// Deep-merge `src` into `dst`: objects merge key-by-key; anything else overwrites.
fn merge(dst: &mut Value, src: &Value) {
    match (dst, src) {
        (Value::Object(d), Value::Object(s)) => {
            for (k, v) in s {
                merge(d.entry(k.clone()).or_insert(Value::Null), v);
            }
        }
        (d, s) => *d = s.clone(),
    }
}

fn navigate<'a>(data: &'a Value, path: &[String]) -> Option<&'a Value> {
    let mut cur = data;
    for seg in path {
        cur = cur.get(seg)?;
    }
    Some(cur)
}

fn navigate_mut<'a>(data: &'a mut Value, path: &[String]) -> Option<&'a mut Value> {
    let mut cur = data;
    for seg in path {
        cur = cur.get_mut(seg)?;
    }
    Some(cur)
}

/// The `_entities` representations for the object(s) at `path`: `{ __typename, <key…> }`
/// for each (an object contributes one; an array contributes one per element).
fn representations(data: &Value, path: &[String], type_name: &str, key: &[String]) -> Value {
    let mut out = Vec::new();
    if let Some(node) = navigate(data, path) {
        collect_reprs(node, type_name, key, &mut out);
    }
    Value::Array(out)
}

fn collect_reprs(node: &Value, type_name: &str, key: &[String], out: &mut Vec<Value>) {
    match node {
        Value::Array(items) => {
            for item in items {
                collect_reprs(item, type_name, key, out);
            }
        }
        Value::Object(_) => {
            let mut repr = Map::new();
            repr.insert("__typename".to_string(), json!(type_name));
            for k in key {
                if let Some(v) = node.get(k) {
                    repr.insert(k.clone(), v.clone());
                }
            }
            out.push(Value::Object(repr));
        }
        _ => {}
    }
}

/// Merge the resolved `entities` back into the tree at `path`, by representation order
/// (an object join point takes the first entity; a list join point takes them positionally).
fn stitch(data: &mut Value, path: &[String], entities: &Value) {
    let Some(node) = navigate_mut(data, path) else {
        return;
    };
    let ents = entities.as_array().cloned().unwrap_or_default();
    match node {
        Value::Array(items) => {
            for (item, ent) in items.iter_mut().zip(ents.iter()) {
                merge(item, ent);
            }
        }
        Value::Object(_) => {
            if let Some(ent) = ents.first() {
                merge(node, ent);
            }
        }
        _ => {}
    }
}

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

    /// The `Own` tenancy class — the class every fetch in these (pre-Stage-5) tests runs under.
    const OWN: &boatramp_core::tenancy::TenancyClass = &boatramp_core::tenancy::TenancyClass::Own;
    use crate::graphql_federation::compose;
    use crate::graphql_plan::plan;
    use std::collections::HashMap;

    const ACCOUNTS: &str = r#"
        type Query { me: User }
        type User @key(fields: "id") { id: ID! name: String }
    "#;
    const ACCOUNTS_LIST: &str = r#"
        type Query { users: [User] }
        type User @key(fields: "id") { id: ID! name: String }
    "#;
    const REVIEWS: &str = r#"
        type Query { topReviews: [Review] }
        type Review { id: ID! body: String }
        extend type User @key(fields: "id") { id: ID! @external reviews: [Review] }
    "#;

    /// A mock runner returning a canned response per subgraph. It is **adversarial about its
    /// input**: it asserts the query the gateway sent actually parses as a GraphQL operation
    /// before answering. A mock that ignores its query manufactures confidence — it passes even
    /// when the planner emits garbage (an anonymous mutation, a dropped argument), which is
    /// exactly how a broken planner shipped green. This one cannot.
    struct Mock(HashMap<&'static str, Value>);

    #[async_trait::async_trait]
    impl SubgraphFetcher for Mock {
        async fn fetch(
            &self,
            subgraph: &str,
            query: &str,
            _variables: Value,
            _class: &boatramp_core::tenancy::TenancyClass,
        ) -> Value {
            assert!(
                async_graphql_parser::parse_query(query).is_ok(),
                "gateway sent subgraph `{subgraph}` an unparsable query: {query}"
            );
            self.0.get(subgraph).cloned().unwrap_or_else(|| json!({}))
        }
    }

    /// A runner that honors the real federation contract instead of returning a canned
    /// answer: a root fetch returns its data; an `_entities` fetch reads the
    /// `representations` variable and resolves each representation **by its key, in
    /// order** — exactly what an async-graphql federation subgraph's `_entities` resolver
    /// does. Using it end-to-end exercises the whole representations→`_entities`→stitch
    /// round-trip against a faithful subgraph, not a stub that echoes the expected result.
    struct ContractRunner;

    #[async_trait::async_trait]
    impl SubgraphFetcher for ContractRunner {
        async fn fetch(
            &self,
            subgraph: &str,
            query: &str,
            variables: Value,
            _class: &boatramp_core::tenancy::TenancyClass,
        ) -> Value {
            match subgraph {
                "accounts" => json!({ "data": { "users": [
                    { "__typename": "User", "id": "1", "name": "Alice" },
                    { "__typename": "User", "id": "2", "name": "Bob" },
                ] } }),
                "reviews" => {
                    assert!(
                        query.contains("_entities"),
                        "entity fetch must use _entities"
                    );
                    let reprs = variables
                        .get("representations")
                        .and_then(|v| v.as_array())
                        .cloned()
                        .unwrap_or_default();
                    let entities: Vec<Value> = reprs
                        .iter()
                        .map(|r| {
                            let id = r.get("id").and_then(|v| v.as_str()).unwrap_or("");
                            json!({ "reviews": [ { "body": format!("review for {id}") } ] })
                        })
                        .collect();
                    json!({ "data": { "_entities": entities } })
                }
                other => json!({ "errors": [{ "message": format!("unknown subgraph {other}") }] }),
            }
        }
    }

    /// An [`Invoker`](boatramp_handlers::Invoker) with no functions deployed — every
    /// target resolves to `NotFound`, so [`invoke_subgraph`] must report the
    /// registered-but-undeployed subgraph precisely.
    struct MissingInvoker;

    #[async_trait::async_trait]
    impl boatramp_handlers::Invoker for MissingInvoker {
        async fn invoke(
            &self,
            _target: &str,
            _request: boatramp_handlers::InvokeRequest,
            _depth: u32,
        ) -> Result<boatramp_handlers::InvokeResponse, boatramp_handlers::InvokeError> {
            Err(boatramp_handlers::InvokeError::NotFound)
        }
    }

    /// An [`Invoker`](boatramp_handlers::Invoker) that reflects the `Authorization` header it
    /// received back into its response — modelling a subgraph that authorizes per field: with a
    /// forwarded bearer it resolves (echoing the identity), without one it refuses with
    /// `UNAUTHENTICATED`. It lets a test prove the gateway forwards the caller's identity on the
    /// invoke path (root and `_entities` alike) rather than dropping it.
    struct AuthEchoInvoker;

    #[async_trait::async_trait]
    impl boatramp_handlers::Invoker for AuthEchoInvoker {
        async fn invoke(
            &self,
            _target: &str,
            request: boatramp_handlers::InvokeRequest,
            _depth: u32,
        ) -> Result<boatramp_handlers::InvokeResponse, boatramp_handlers::InvokeError> {
            let authz = request
                .headers
                .iter()
                .find(|(k, _)| k.eq_ignore_ascii_case("authorization"))
                .map(|(_, v)| String::from_utf8_lossy(v).into_owned());
            let body = match authz {
                Some(value) => json!({ "data": { "identity": value } }),
                None => json!({ "errors": [
                    { "message": "unauthenticated", "extensions": { "code": "UNAUTHENTICATED" } }
                ] }),
            };
            Ok(boatramp_handlers::InvokeResponse {
                status: 200,
                headers: vec![("content-type".to_string(), b"application/json".to_vec())],
                body: serde_json::to_vec(&body).unwrap(),
            })
        }
    }

    #[tokio::test]
    async fn merges_root_fetches_from_distinct_subgraphs() {
        let sg = compose(&[
            ("accounts".into(), ACCOUNTS.into()),
            ("reviews".into(), REVIEWS.into()),
        ])
        .unwrap();
        let plan = plan("{ me { name } topReviews { body } }", &sg).unwrap();
        let mock = Mock(HashMap::from([
            ("accounts", json!({ "data": { "me": { "name": "Alice" } } })),
            (
                "reviews",
                json!({ "data": { "topReviews": [{ "body": "ok" }] } }),
            ),
        ]));
        let out = execute(&plan, &mock, &json!({})).await;
        assert_eq!(out["data"]["me"]["name"], json!("Alice"));
        assert_eq!(out["data"]["topReviews"][0]["body"], json!("ok"));
        // A wholly-successful query carries no `errors` key (byte-identical to before).
        assert!(out.get("errors").is_none(), "no errors on success: {out}");
    }

    #[tokio::test]
    async fn a_fully_errored_root_nulls_data_and_surfaces_the_error() {
        // A subgraph returns a spec-correct `{ data: null, errors: [...] }` and it is the only
        // root fetch, so nothing resolves. The gateway must forward the real message AND, per
        // GraphQL error propagation, null the whole `data` (a fully-errored non-nullable root
        // field nulls `data`) — not leave it a bare `{}`.
        let sg = compose(&[
            ("accounts".into(), ACCOUNTS.into()),
            ("reviews".into(), REVIEWS.into()),
        ])
        .unwrap();
        let plan = plan("{ me { name } }", &sg).unwrap();
        let mock = Mock(HashMap::from([(
            "accounts",
            json!({ "data": null, "errors": [{ "message": "boom", "path": ["me"] }] }),
        )]));
        let out = execute(&plan, &mock, &json!({})).await;
        assert_eq!(out["errors"][0]["message"], json!("boom"));
        assert_eq!(out["errors"][0]["path"], json!(["me"]));
        // Nothing resolved → `data` is null (not `{}`), and the `{"errors":…}` object was never
        // merged as data.
        assert_eq!(out["data"], json!(null));
    }

    #[tokio::test]
    async fn partial_success_keeps_the_healthy_subgraph_and_surfaces_the_other_error() {
        // Two root fetches: one succeeds, one errors. The successful field survives in `data`
        // and the failing field's error surfaces — a partial failure is not a total wipe.
        let sg = compose(&[
            ("accounts".into(), ACCOUNTS.into()),
            ("reviews".into(), REVIEWS.into()),
        ])
        .unwrap();
        let plan = plan("{ me { name } topReviews { body } }", &sg).unwrap();
        let mock = Mock(HashMap::from([
            ("accounts", json!({ "data": { "me": { "name": "Alice" } } })),
            (
                "reviews",
                json!({ "data": null, "errors": [{ "message": "reviews down", "path": ["topReviews"] }] }),
            ),
        ]));
        let out = execute(&plan, &mock, &json!({})).await;
        // `data` is NOT nulled — a partial success is preserved (contrast the fully-errored case).
        assert!(!out["data"].is_null(), "partial success keeps data: {out}");
        assert_eq!(out["data"]["me"]["name"], json!("Alice"));
        assert_eq!(out["data"]["topReviews"], json!(null));
        assert_eq!(out["errors"][0]["message"], json!("reviews down"));
    }

    #[tokio::test]
    async fn an_entities_fetch_error_is_surfaced_with_the_provider_path() {
        // A dependent `_entities` fetch errors. Its error is surfaced, prefixed with the
        // provider path (`me`), while the root subgraph's data survives.
        let sg = compose(&[
            ("accounts".into(), ACCOUNTS.into()),
            ("reviews".into(), REVIEWS.into()),
        ])
        .unwrap();
        let plan = plan("{ me { name reviews { body } } }", &sg).unwrap();
        let mock = Mock(HashMap::from([
            (
                "accounts",
                json!({ "data": { "me": { "name": "Alice", "__typename": "User", "id": "1" } } }),
            ),
            (
                "reviews",
                json!({ "errors": [{ "message": "FORBIDDEN", "path": ["_entities", 0, "reviews"] }] }),
            ),
        ]));
        let out = execute(&plan, &mock, &json!({})).await;
        // Root data intact; the entity error surfaces with the provider path prefixed.
        assert_eq!(out["data"]["me"]["name"], json!("Alice"));
        assert_eq!(out["errors"][0]["message"], json!("FORBIDDEN"));
        assert_eq!(
            out["errors"][0]["path"],
            json!(["me", "_entities", 0, "reviews"])
        );
    }

    #[tokio::test]
    async fn stitches_a_cross_subgraph_entity_field() {
        let sg = compose(&[
            ("accounts".into(), ACCOUNTS.into()),
            ("reviews".into(), REVIEWS.into()),
        ])
        .unwrap();
        let plan = plan("{ me { name reviews { body } } }", &sg).unwrap();
        let mock = Mock(HashMap::from([
            (
                "accounts",
                json!({ "data": { "me": { "name": "Alice", "__typename": "User", "id": "1" } } }),
            ),
            (
                "reviews",
                json!({ "data": { "_entities": [{ "reviews": [{ "body": "great" }] }] } }),
            ),
        ]));
        let out = execute(&plan, &mock, &json!({})).await;
        // The `me` object now carries both its accounts fields and the stitched reviews.
        assert_eq!(out["data"]["me"]["name"], json!("Alice"));
        assert_eq!(out["data"]["me"]["reviews"][0]["body"], json!("great"));
    }

    #[tokio::test]
    async fn executes_a_list_entity_fetch_joining_each_element_by_its_key() {
        let sg = compose(&[
            ("accounts".into(), ACCOUNTS_LIST.into()),
            ("reviews".into(), REVIEWS.into()),
        ])
        .unwrap();
        let plan = plan("{ users { name reviews { body } } }", &sg).unwrap();
        let out = execute(&plan, &ContractRunner, &json!({})).await;
        // Each list element is joined to *its own* reviews by key — proving the
        // representations→`_entities`→stitch round-trip preserves per-element identity
        // (element 2 gets review-for-2, not review-for-1), which a canned mock can't show.
        assert_eq!(out["data"]["users"][0]["name"], json!("Alice"));
        assert_eq!(
            out["data"]["users"][0]["reviews"][0]["body"],
            json!("review for 1")
        );
        assert_eq!(out["data"]["users"][1]["name"], json!("Bob"));
        assert_eq!(
            out["data"]["users"][1]["reviews"][0]["body"],
            json!("review for 2")
        );
    }

    // A subgraph owning a `Mutation` root field (plus a query, as a subgraph conventionally has).
    const AGENT: &str = r#"
        type Query { ping: String }
        type Mutation { agent(input: String): String }
    "#;

    /// A subgraph fetcher that is **adversarial about a mutation**: it refuses unless the query it
    /// received is a genuine `mutation` operation carrying its argument (and, for the variable
    /// form, the forwarded variable value). This is the regression guard for the shipped bug —
    /// the planner dispatched a Mutation as an anonymous query and dropped arguments/variables, so
    /// the resolver never ran (`data:null`). A test double that echoed a canned answer could not
    /// tell; this one asserts the contract the real subgraph would enforce.
    struct MutationRunner;

    #[async_trait::async_trait]
    impl SubgraphFetcher for MutationRunner {
        async fn fetch(
            &self,
            subgraph: &str,
            query: &str,
            variables: Value,
            _class: &boatramp_core::tenancy::TenancyClass,
        ) -> Value {
            assert_eq!(subgraph, "agent");
            let doc = async_graphql_parser::parse_query(query)
                .unwrap_or_else(|e| panic!("mutation fetch didn't parse: {e}\nquery: {query}"));
            // It MUST be a mutation operation — an anonymous/query op is the shipped bug.
            let op = match &doc.operations {
                async_graphql_parser::types::DocumentOperations::Single(op) => &op.node,
                async_graphql_parser::types::DocumentOperations::Multiple(m) => {
                    &m.values().next().unwrap().node
                }
            };
            assert_eq!(
                op.ty,
                async_graphql_parser::types::OperationType::Mutation,
                "the gateway must dispatch a Mutation as a `mutation`, got: {query}"
            );
            // The argument must have arrived — either an inline value or a forwarded variable.
            let inline = query.contains("agent(input:");
            let via_var = variables.get("input").is_some();
            assert!(
                inline && (query.contains("\"hi\"") || via_var),
                "the mutation argument was dropped; query={query} vars={variables}"
            );
            json!({ "data": { "agent": "ok" } })
        }
    }

    #[tokio::test]
    async fn executes_a_federated_mutation_dispatching_it_as_a_mutation_with_arguments() {
        // The exact class that shipped broken: a federated mutation with an argument, driven
        // through the real plan()→execute() path. MutationRunner asserts the subgraph actually
        // received a `mutation { agent(input: …) }`, so a regression (anonymous op or dropped
        // arg) fails here instead of silently returning data:null in production.
        let sg = compose(&[
            ("accounts".into(), ACCOUNTS.into()),
            ("agent".into(), AGENT.into()),
        ])
        .unwrap();

        // Inline-argument form.
        let plan_inline = plan("mutation { agent(input: \"hi\") }", &sg).unwrap();
        let out = execute(&plan_inline, &MutationRunner, &json!({})).await;
        assert_eq!(out["data"]["agent"], json!("ok"), "out: {out}");

        // Variable form — the common client shape; the variable value must be forwarded.
        let plan_var = plan("mutation T($input: String){ agent(input: $input) }", &sg).unwrap();
        let out = execute(&plan_var, &MutationRunner, &json!({ "input": "hi" })).await;
        assert_eq!(out["data"]["agent"], json!("ok"), "out: {out}");
    }

    #[tokio::test]
    async fn a_function_subgraph_that_is_not_deployed_is_reported_precisely() {
        // A router with no SQL subgraphs routes every fetch to the invoke path.
        let router = BackendRouter::new(
            std::sync::Arc::new(MissingInvoker),
            "default".to_string(),
            None,
            std::collections::BTreeMap::new(),
            None,
        );
        let resp = router
            .fetch("accounts", "{ me { id } }", json!({}), OWN)
            .await;
        let msg = resp["errors"][0]["message"].as_str().unwrap_or_default();
        assert!(
            msg.contains("no function named `accounts` is deployed"),
            "unexpected error: {msg}"
        );
    }

    #[test]
    fn target_root_fields_lists_only_the_target_fields_a_query_uses() {
        let sdl = r#"
            type Query {
              me: User
              publicProducts: [Product] @tenant(scope: target, via: [domain], public: "storefront")
            }
            type User { id: ID! }
            type Product { id: ID! }
        "#;
        let sg = crate::graphql_federation::compose(&[("shop".into(), sdl.into())]).unwrap();
        // An own-only query has no target fields; a query using the target field lists it; a mixed
        // query lists only the target one — so the operator gate refuses exactly the offending field.
        assert!(target_root_fields("{ me { id } }", &sg).is_empty());
        assert_eq!(
            target_root_fields("{ publicProducts { id } }", &sg),
            vec!["publicProducts".to_string()]
        );
        assert_eq!(
            target_root_fields("{ me { id } publicProducts { id } }", &sg),
            vec!["publicProducts".to_string()]
        );
    }

    #[test]
    fn build_target_scope_lowers_schema_public_subsets() {
        use crate::graphql_data::policy::{ResolvedTerm, RowOp};
        use boatramp_core::sql::SqlValue;
        use boatramp_core::tenancy::{
            PublicCmp, PublicLiteral, PublicPredicate, PublicSubset, PublicTerm, TableScope,
            TenancySchema,
        };
        use std::collections::BTreeMap;

        let mut schema = TenancySchema {
            default_tenant_key: "tenant_id".into(),
            tables: BTreeMap::from([
                ("products".into(), TableScope::Tenant),
                // A table with a public subset but NO tenant scope: omitted from the target map
                // (a target read of it is refused, deny-by-default).
                ("countries".into(), TableScope::Unscoped),
                // A Tenant table whose public subset is EMPTY: omitted (load-time fail-closed — an
                // empty predicate would confine only to `tenant = B`, a match-all over B's rows).
                ("legacy".into(), TableScope::Tenant),
            ]),
            ..Default::default()
        };
        let subset = PublicSubset {
            predicate: PublicPredicate {
                terms: vec![
                    PublicTerm::Cmp {
                        column: "published".into(),
                        op: PublicCmp::Eq,
                        value: PublicLiteral::Bool(true),
                    },
                    PublicTerm::Null {
                        column: "deleted_at".into(),
                        negated: false,
                    },
                ],
            },
            world_public: true,
            listable: true,
        };
        schema
            .public_subsets
            .insert("products".into(), subset.clone());
        schema.public_subsets.insert("countries".into(), subset);
        schema.public_subsets.insert(
            "legacy".into(),
            PublicSubset {
                predicate: PublicPredicate { terms: vec![] },
                world_public: true,
                listable: false,
            },
        );

        let scope = build_target_scope(&schema, SqlValue::Text("tenant_B".into()));
        assert_eq!(scope.tenant_value, SqlValue::Text("tenant_B".into()));
        // `products` (Tenant) is target-readable, confined on its tenant column + the lowered public
        // predicate; `countries` (Unscoped, no tenant column) and `legacy` (empty predicate) are
        // both omitted (deny-by-default).
        assert!(!scope.tables.contains_key("countries"));
        assert!(
            !scope.tables.contains_key("legacy"),
            "an empty public predicate is omitted (load-time fail-closed), never a match-all"
        );
        let products = scope.tables.get("products").expect("products confined");
        assert_eq!(products.tenant_column, "tenant_id");
        assert_eq!(
            products.public,
            vec![
                ResolvedTerm::Cmp {
                    column: "published".into(),
                    op: RowOp::Eq,
                    value: SqlValue::Boolean(true),
                },
                ResolvedTerm::Null {
                    column: "deleted_at".into(),
                    negated: false,
                },
            ]
        );
    }

    #[tokio::test]
    async fn a_target_fetch_with_no_resolved_scope_fails_closed() {
        // A Target-class fetch when the request resolved NO target scope (router.target == None) is
        // refused BEFORE any invoke/SQL — a target read never runs un-confined (deny-by-default).
        let router = BackendRouter::new(
            std::sync::Arc::new(MissingInvoker),
            "default".to_string(),
            None,
            std::collections::BTreeMap::new(),
            None,
        );
        let target_class = boatramp_core::tenancy::TenancyClass::Target {
            via: vec![boatramp_core::tenancy::TargetSource::Domain],
            public: "storefront".into(),
            write: vec![],
        };
        let resp = router
            .fetch("accounts", "{ me { id } }", json!({}), &target_class)
            .await;
        let msg = resp["errors"][0]["message"].as_str().unwrap_or_default();
        assert!(
            msg.contains("target-tenant scope was not resolved"),
            "a target fetch with no resolved scope must fail closed, got: {msg}"
        );
    }

    #[tokio::test]
    async fn forwards_the_callers_verified_bearer_to_a_function_subgraph() {
        let router = BackendRouter::new(
            std::sync::Arc::new(AuthEchoInvoker),
            "default".to_string(),
            None,
            std::collections::BTreeMap::new(),
            Some("t-acme".to_string()),
        );
        // A root fetch carries the caller's identity as `Bearer <token>`...
        let root = router
            .fetch("orders", "{ me { id } }", json!({}), OWN)
            .await;
        assert_eq!(root["data"]["identity"], json!("Bearer t-acme"));
        // ...and so does a dependent `_entities` hydration fetch (same dispatch path).
        let entity = router
            .fetch(
                "orders",
                "query($r: [_Any!]!) { _entities(representations: $r) { id } }",
                json!({ "representations": [{ "__typename": "Order", "id": "1" }] }),
                OWN,
            )
            .await;
        assert_eq!(
            entity["data"]["identity"],
            json!("Bearer t-acme"),
            "the bearer must ride the _entities fetch too, or a stitched field would go anonymous"
        );
    }

    #[tokio::test]
    async fn an_anonymous_gateway_call_forwards_no_bearer_so_an_authed_field_is_refused() {
        let router = BackendRouter::new(
            std::sync::Arc::new(AuthEchoInvoker),
            "default".to_string(),
            None,
            std::collections::BTreeMap::new(),
            None,
        );
        let resp = router
            .fetch("orders", "{ me { id } }", json!({}), OWN)
            .await;
        assert_eq!(
            resp["errors"][0]["extensions"]["code"],
            json!("UNAUTHENTICATED"),
            "with no forwarded identity a subgraph's authed field must refuse, not resolve anonymously"
        );
    }

    #[test]
    fn merge_is_a_deep_object_merge() {
        let mut a = json!({ "me": { "name": "x" } });
        merge(&mut a, &json!({ "me": { "age": 3 }, "other": 1 }));
        assert_eq!(a, json!({ "me": { "name": "x", "age": 3 }, "other": 1 }));
    }

    /// An invoker that reflects the call-chain `depth` it was dispatched at back into its
    /// response, so a test can prove `BackendRouter::at_depth` threads the guest's depth through
    /// to the sub-fetch (the recursion-safety guarantee).
    struct DepthEchoInvoker;

    #[async_trait::async_trait]
    impl boatramp_handlers::Invoker for DepthEchoInvoker {
        async fn invoke(
            &self,
            _target: &str,
            _request: boatramp_handlers::InvokeRequest,
            depth: u32,
        ) -> Result<boatramp_handlers::InvokeResponse, boatramp_handlers::InvokeError> {
            Ok(boatramp_handlers::InvokeResponse {
                status: 200,
                headers: vec![("content-type".to_string(), b"application/json".to_vec())],
                body: serde_json::to_vec(&json!({ "data": { "depth": depth } })).unwrap(),
            })
        }
    }

    #[tokio::test]
    async fn at_depth_dispatches_function_fetches_at_that_depth() {
        // The external gateway is the root (depth 0)...
        let root = BackendRouter::new(
            std::sync::Arc::new(DepthEchoInvoker),
            "default".to_string(),
            None,
            std::collections::BTreeMap::new(),
            None,
        );
        assert_eq!(
            root.fetch("s", "{ x }", json!({}), OWN).await["data"]["depth"],
            json!(0)
        );
        // ...a guest-initiated run dispatches its sub-fetches at its own depth, so the shared
        // invoke cap counts a run → subgraph → run chain and stops it looping.
        let scoped = BackendRouter::new(
            std::sync::Arc::new(DepthEchoInvoker),
            "default".to_string(),
            None,
            std::collections::BTreeMap::new(),
            None,
        )
        .at_depth(4);
        assert_eq!(
            scoped.fetch("s", "{ x }", json!({}), OWN).await["data"]["depth"],
            json!(4)
        );
    }
}