gql 0.3.2

A GraphQL reference implementation for Rust.
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
//! Query complexity and depth analysis.
//!
//! The analyzer walks an operation the way the executor would — expanding fragments, respecting
//! `@skip` and `@include`, and merging selections that share a response key — without running a
//! single resolver. It is meant to be called before execution so an oversized query is rejected
//! instead of tying up a worker.

use std::{borrow::Cow, sync::Arc};

use rustc_hash::{FxHashMap, FxHashSet};
use smallvec::SmallVec;

use crate::{
    Object, Value,
    ast::{self, OperationKind},
    error::GraphQLError,
    schema::Schema,
    types::{Field, Type, TypeKind, TypeRef},
};

/// Inputs for a complexity analysis.
#[derive(Clone, Copy, Debug)]
pub struct ComplexityOptions {
    /// Multiplier applied to list fields.
    pub list_factor: u32,
    /// Cost of a field with no explicit estimator.
    pub field_cost: u32,
    /// Maximum estimated complexity. Zero disables the limit.
    pub max_complexity: u32,
    /// Maximum selection depth. Zero disables the limit.
    pub max_depth: usize,
    /// Maximum number of distinct fields in any one selection set after fragment expansion.
    ///
    /// This bounds wide, heavily aliased queries that stay shallow. Zero disables the limit.
    pub max_breadth: usize,
}

impl Default for ComplexityOptions {
    fn default() -> Self {
        Self {
            list_factor: 10,
            field_cost: 1,
            max_complexity: 0,
            max_depth: 0,
            max_breadth: 0,
        }
    }
}

/// The result of analysing an operation.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Complexity {
    /// Estimated total cost.
    pub cost: u32,
    /// Selection-set depth.
    pub depth: usize,
    /// The largest number of distinct response keys in any one selection set.
    pub breadth: usize,
}

/// Estimate the cost of the selected operation.
///
/// # Errors
///
/// Returns an error when the operation is unknown, ambiguous, or exceeds a configured limit.
pub fn analyze(
    schema: &Schema,
    document: &ast::Document<'_>,
    operation_name: Option<&str>,
    variables: &Object,
    options: &ComplexityOptions,
) -> Result<Complexity, GraphQLError> {
    let operation = select_operation(document, operation_name)?;
    analyze_operation(schema, document, operation, variables, options)
}

/// Estimate the cost of an operation that has already been selected.
///
/// A prepared query selects its operation once, at preparation time, so it can use this entry
/// point and skip the document scan [`analyze`] performs on every request.
///
/// # Errors
///
/// Returns an error when the operation exceeds a configured limit.
pub(crate) fn analyze_operation(
    schema: &Schema,
    document: &ast::Document<'_>,
    operation: &ast::OperationDefinition<'_>,
    variables: &Object,
    options: &ComplexityOptions,
) -> Result<Complexity, GraphQLError> {
    let root = root_type_name(schema, operation.kind)?;

    let mut analyzer = Analyzer {
        schema,
        document,
        variables,
        options,
        fragment_cache: FragmentCache::new(),
        work: 0,
        breadth: 0,
    };
    let mut active_fragments = SmallVec::new();
    let (cost, depth) = analyzer.analyze_selection(
        operation.selection_set.items.iter(),
        &root,
        1,
        &mut active_fragments,
    )?;
    let breadth = analyzer.breadth;

    if options.max_complexity != 0 && cost > options.max_complexity {
        return Err(GraphQLError::new(format!(
            "Query complexity {cost} exceeds the maximum allowed complexity of {}.",
            options.max_complexity
        )));
    }
    if options.max_depth != 0 && depth > options.max_depth {
        return Err(GraphQLError::new(format!(
            "Query depth {depth} exceeds the maximum allowed depth of {}.",
            options.max_depth
        )));
    }
    if options.max_breadth != 0 && breadth > options.max_breadth {
        return Err(GraphQLError::new(format!(
            "Query breadth {breadth} exceeds the maximum allowed breadth of {}.",
            options.max_breadth
        )));
    }

    Ok(Complexity {
        cost,
        depth,
        breadth,
    })
}

/// Select the operation the caller asked for, using the same rules as execution.
fn select_operation<'document, 'source>(
    document: &'document ast::Document<'source>,
    operation_name: Option<&str>,
) -> Result<&'document ast::OperationDefinition<'source>, GraphQLError> {
    if let Some(name) = operation_name {
        return document
            .operations()
            .find(|operation| operation.name == Some(name))
            .ok_or_else(|| GraphQLError::new(format!("Unknown operation named \"{name}\".")));
    }

    let mut operations = document.operations();
    match operations.next() {
        None => Err(GraphQLError::new("Must provide an operation.")),
        Some(first) if operations.next().is_none() => Ok(first),
        Some(_) => Err(GraphQLError::new(
            "Must provide an operation name if the document contains multiple operations.",
        )),
    }
}

fn root_type_name(schema: &Schema, kind: OperationKind) -> Result<Arc<str>, GraphQLError> {
    match kind {
        // The schema already interns its root names, so the common case shares that allocation.
        OperationKind::Query => Ok(Arc::clone(schema.query_name())),
        OperationKind::Mutation => schema
            .mutation_name()
            .map(Arc::clone)
            .ok_or_else(|| GraphQLError::new("Schema is not configured for mutations.")),
        OperationKind::Subscription => schema
            .subscription_name()
            .map(Arc::clone)
            .ok_or_else(|| GraphQLError::new("Schema is not configured for subscriptions.")),
    }
}

/// Maximum fragment nesting accepted by the analyzer.
const MAX_FRAGMENT_DEPTH: usize = 128;
/// Maximum number of selections the analyzer may visit before rejecting the operation.
const MAX_ANALYSIS_WORK: u64 = 500_000;

/// A field selection after fragment expansion and duplicate-response-key merging.
#[derive(Clone)]
struct CollectedField<'source, 'document> {
    response_key: &'source str,
    /// The type the field is selected on, which may be narrower than the enclosing type after a
    /// fragment with a type condition.
    scope: Arc<str>,
    node: &'document ast::Field<'source>,
    /// Sub-selections of every field merged under this response key.
    selections: SmallVec<[&'document ast::Selection<'source>; 4]>,
}

/// The fields of one selection set after flattening.
///
/// Selection sets overwhelmingly hold a handful of fields, and analysis allocates this for every
/// one of them, so the common shapes (up to eight fields) stay inline.
type CollectedFields<'source, 'document> = SmallVec<[CollectedField<'source, 'document>; 8]>;

/// A memoised fragment expansion: the fragment name, the scope it was expanded for, and the
/// resulting fields.
type CachedFragment<'source, 'document> =
    (&'source str, Arc<str>, CollectedFields<'source, 'document>);

/// Fragment expansions memoised for one analysis.
///
/// Documents define only a handful of fragments and analysis visits each one a handful of times,
/// so a linear scan over an inline list is both faster and allocation-free compared to hashing.
struct FragmentCache<'source, 'document> {
    entries: SmallVec<[CachedFragment<'source, 'document>; 8]>,
    index: Option<FxHashMap<(&'source str, Arc<str>), usize>>,
}

impl<'source, 'document> FragmentCache<'source, 'document> {
    fn new() -> Self {
        Self {
            entries: SmallVec::new(),
            index: None,
        }
    }

    fn get(&self, key: &(&'source str, Arc<str>)) -> Option<&[CollectedField<'source, 'document>]> {
        match &self.index {
            Some(index) => index
                .get(key)
                .map(|position| self.entries[*position].2.as_slice()),
            None => self
                .entries
                .iter()
                .find(|(name, scope, _)| *name == key.0 && scope == &key.1)
                .map(|(_, _, fields)| fields.as_slice()),
        }
    }

    fn insert(
        &mut self,
        key: (&'source str, Arc<str>),
        fields: CollectedFields<'source, 'document>,
    ) {
        let position = self.entries.len();
        self.entries.push((key.0, key.1, fields));
        match &mut self.index {
            Some(index) => {
                index.insert(
                    (
                        self.entries[position].0,
                        Arc::clone(&self.entries[position].1),
                    ),
                    position,
                );
            }
            None if self.entries.len() > LINEAR_INDEX_LIMIT => {
                self.index = Some(
                    self.entries
                        .iter()
                        .enumerate()
                        .map(|(position, (name, scope, _))| ((*name, Arc::clone(scope)), position))
                        .collect(),
                );
            }
            None => {}
        }
    }
}

/// Above this many entries a hash index beats a linear scan.
const LINEAR_INDEX_LIMIT: usize = 16;

struct Analyzer<'a, 'document, 'source> {
    schema: &'a Schema,
    document: &'document ast::Document<'source>,
    variables: &'a Object,
    options: &'a ComplexityOptions,
    fragment_cache: FragmentCache<'source, 'document>,
    work: u64,
    breadth: usize,
}

impl<'a, 'document, 'source> Analyzer<'a, 'document, 'source> {
    /// Analyze one selection set and return its cost and deepest nesting level.
    fn analyze_selection<I>(
        &mut self,
        items: I,
        scope: &Arc<str>,
        depth: usize,
        active_fragments: &mut SmallVec<[&'source str; 8]>,
    ) -> Result<(u32, usize), GraphQLError>
    where
        I: IntoIterator<Item = &'document ast::Selection<'source>>,
    {
        let mut collected: CollectedFields<'source, 'document> = SmallVec::new();
        let mut index = FieldIndex::new();
        self.collect_fields(items, scope, active_fragments, &mut collected, &mut index)?;
        self.breadth = self.breadth.max(distinct_response_keys(&collected));

        // Every field in the set is looked up on the same parent type, so it is resolved once for
        // the set instead of once per field. A field merged from a fragment with a narrower scope
        // carries its own scope and resolves that separately.
        let parent_type = self.schema.get_type(scope);
        let mut cost = 0u32;
        let mut max_depth = depth;
        for field in &collected {
            let (field_cost, field_depth) =
                self.analyze_field(field, parent_type, scope, depth, active_fragments)?;
            cost = cost.saturating_add(field_cost);
            max_depth = max_depth.max(field_depth);
        }
        Ok((cost, max_depth))
    }

    /// Flatten a selection set into fields, expanding fragments and merging duplicate response
    /// keys. Directives are evaluated here so skipped selections never contribute cost.
    ///
    /// Fragment expansions are memoised by `(fragment, scope)`. Without that cache a document
    /// where each fragment spreads the previous one twice expands exponentially even though the
    /// merged result is tiny, which would let a client burn arbitrary CPU before a complexity
    /// limit is ever compared.
    fn collect_fields<I>(
        &mut self,
        items: I,
        scope: &Arc<str>,
        active_fragments: &mut SmallVec<[&'source str; 8]>,
        output: &mut CollectedFields<'source, 'document>,
        index: &mut FieldIndex<'source>,
    ) -> Result<(), GraphQLError>
    where
        I: IntoIterator<Item = &'document ast::Selection<'source>>,
    {
        for selection in items {
            self.work = self.work.saturating_add(1);
            if self.work > MAX_ANALYSIS_WORK {
                return Err(GraphQLError::new(
                    "The query expands to too many fields to analyse safely.",
                ));
            }
            if !self.is_included(selection.directives()) {
                continue;
            }

            match selection {
                ast::Selection::Field(field) => {
                    merge_field(output, index, field, scope);
                }
                ast::Selection::FragmentSpread(spread) => {
                    if active_fragments.contains(&spread.name) {
                        // A fragment cycle is a validation error; guard against it so analysis can
                        // never hang or overflow the stack.
                        continue;
                    }
                    let Some(fragment) = self.document.fragment(spread.name) else {
                        continue;
                    };
                    if !self.is_included(&fragment.directives) {
                        continue;
                    }
                    let Some(effective_scope) =
                        fragment_scope(self.schema, fragment.type_condition, scope)
                    else {
                        continue;
                    };
                    if active_fragments.len() >= MAX_FRAGMENT_DEPTH {
                        return Err(GraphQLError::new(format!(
                            "Fragment nesting exceeds the maximum of {MAX_FRAGMENT_DEPTH}."
                        )));
                    }

                    let key = (spread.name, Arc::clone(&effective_scope));
                    if let Some(fields) = self.fragment_cache.get(&key) {
                        merge_all(output, index, fields);
                        continue;
                    }

                    let mut fields = SmallVec::new();
                    let mut fragment_index = FieldIndex::new();
                    active_fragments.push(spread.name);
                    let result = self.collect_fields(
                        fragment.selection_set.items.iter(),
                        &effective_scope,
                        active_fragments,
                        &mut fields,
                        &mut fragment_index,
                    );
                    active_fragments.pop();
                    result?;
                    merge_all(output, index, &fields);
                    self.fragment_cache.insert(key, fields);
                }
                ast::Selection::InlineFragment(fragment) => {
                    let effective_scope = match fragment.type_condition {
                        Some(condition) => match fragment_scope(self.schema, condition, scope) {
                            Some(scope) => scope,
                            None => continue,
                        },
                        None => Arc::clone(scope),
                    };
                    self.collect_fields(
                        fragment.selection_set.items.iter(),
                        &effective_scope,
                        active_fragments,
                        output,
                        index,
                    )?;
                }
            }
        }
        Ok(())
    }

    fn analyze_field(
        &mut self,
        field: &CollectedField<'source, 'document>,
        parent_type: Option<&'a Type>,
        parent_scope: &str,
        depth: usize,
        active_fragments: &mut SmallVec<[&'source str; 8]>,
    ) -> Result<(u32, usize), GraphQLError> {
        // The field's definition is needed for both its cost and its return type, so it is
        // resolved once instead of once per question.
        let definition = if field.scope.as_ref() == parent_scope {
            field_definition_on(parent_type, field.node.name)
        } else {
            self.field_definition(&field.scope, field.node.name)
        };
        let base = self.field_cost(field, definition);

        if field.selections.is_empty() {
            return Ok((base, depth));
        }

        let return_type = match definition {
            Some(definition) => Cow::Borrowed(&definition.ty),
            None => match meta_field_type(field.node.name) {
                Some(ty) => ty,
                // An unknown field is a validation error. Be defensive: charge its base cost and
                // do not try to descend into a type we cannot resolve.
                None => return Ok((base, depth)),
            },
        };

        let multiplier = list_multiplier(&return_type, self.options.list_factor);
        let named_type = return_type.named_type().clone();
        let (selection_cost, selection_depth) = self.analyze_selection(
            field.selections.iter().copied(),
            &named_type,
            depth.saturating_add(1),
            active_fragments,
        )?;

        let total = base.saturating_add(selection_cost.saturating_mul(multiplier));
        Ok((total, selection_depth))
    }

    fn field_cost(
        &self,
        field: &CollectedField<'source, 'document>,
        definition: Option<&Field>,
    ) -> u32 {
        let Some(definition) = definition else {
            return self.options.field_cost;
        };
        let Some(estimator) = &definition.complexity else {
            return self.options.field_cost;
        };
        // Validation reports argument errors before this runs; if coercion still fails, fall back
        // to defaults rather than rejecting the whole analysis.
        let args = crate::execution::coerce_argument_values(
            self.schema,
            definition,
            field.node,
            self.variables,
        )
        .unwrap_or_default();
        estimator(&args)
    }

    fn field_definition(&self, scope: &str, name: &str) -> Option<&Field> {
        field_definition_on(self.schema.get_type(scope), name)
    }

    /// Evaluate `@skip` and `@include`.
    ///
    /// A variable that is missing or not a boolean is treated as `false`, which is what validation
    /// assumed when it let the document through.
    fn is_included(&self, directives: &[ast::Directive<'source>]) -> bool {
        for directive in directives {
            match directive.name {
                "skip" => {
                    if directive_if(directive, self.variables).unwrap_or(false) {
                        return false;
                    }
                }
                "include" => {
                    if !directive_if(directive, self.variables).unwrap_or(false) {
                        return false;
                    }
                }
                _ => {}
            }
        }
        true
    }
}

/// A conservative, variable-independent upper bound on an operation's limits.
///
/// A prepared query analyses its document once, at preparation time. That analysis cannot use the
/// request's variables, so it deliberately over-estimates: every `@skip`/`@include` branch is
/// counted, duplicate response keys are charged once per occurrence, and list multipliers are kept
/// symbolic (one coefficient per list-nesting level) so a request can plug in its own
/// [`ComplexityOptions::list_factor`] at execution time.
///
/// The bound is only an answer for limits it can prove: if any reachable field — leaf or not — has
/// a custom complexity estimator, whose result depends on runtime argument values, no bound is
/// produced and the operation falls back to the exact per-request analysis. An estimator on a leaf
/// field is just as variable-dependent as one on a field with a selection set, so both disable the
/// bound.
pub(crate) struct StaticComplexity {
    /// `coefficients[i]` is the number of cost units multiplied by `list_factor^i`.
    coefficients: SmallVec<[u64; 4]>,
    /// Selection-set nesting depth, in the same unit as [`Complexity::depth`].
    depth: usize,
    /// The largest number of distinct response keys in any one selection set.
    breadth: usize,
}

impl StaticComplexity {
    /// Whether this bound proves the operation fits every configured limit.
    ///
    /// A `false` answer is not a rejection: it only means the exact analysis has to run so the
    /// real cost can be compared (and, if it is too large, reported with the usual message).
    pub(crate) fn within_limits(&self, options: &ComplexityOptions) -> bool {
        if options.max_depth != 0 && self.depth > options.max_depth {
            return false;
        }
        if options.max_breadth != 0 && self.breadth > options.max_breadth {
            return false;
        }
        if options.max_complexity != 0 {
            let mut cost = 0u64;
            let mut factor = 1u64;
            for coefficient in &self.coefficients {
                cost = cost.saturating_add(coefficient.saturating_mul(factor));
                factor = factor.saturating_mul(u64::from(options.list_factor));
            }
            if cost > u64::from(options.max_complexity) {
                return false;
            }
        }
        true
    }
}

/// Compute a conservative upper bound for an already selected operation.
///
/// Returns `None` when the bound cannot be proven (a custom complexity estimator, an unexpected
/// expansion, an unresolved fragment or the analysis work limit). The caller then falls back to
/// [`analyze_operation`] so behaviour is never weakened.
pub(crate) fn static_bound(
    schema: &Schema,
    document: &ast::Document<'_>,
    operation: &ast::OperationDefinition<'_>,
) -> Option<StaticComplexity> {
    let root = root_type_name(schema, operation.kind).ok()?;
    let mut analyzer = StaticAnalyzer {
        schema,
        document,
        work: 0,
        breadth: 0,
    };
    let mut active_fragments = SmallVec::new();
    let mut keys = SmallVec::new();
    let bound = analyzer
        .analyze_selection(
            operation.selection_set.items.iter(),
            &root,
            1,
            &mut active_fragments,
            &mut keys,
        )
        .ok()?;
    Some(StaticComplexity {
        coefficients: bound.coefficients,
        depth: bound.depth,
        breadth: analyzer.breadth,
    })
}

/// A cost expression grouped by list-nesting level, plus the depth seen so far.
#[derive(Default)]
struct StaticBound {
    coefficients: SmallVec<[u64; 4]>,
    depth: usize,
}

impl StaticBound {
    fn add(&mut self, exponent: usize, amount: u64) {
        if amount == 0 {
            return;
        }
        if self.coefficients.len() <= exponent {
            self.coefficients.resize(exponent + 1, 0);
        }
        self.coefficients[exponent] = self.coefficients[exponent].saturating_add(amount);
    }

    /// Fold a nested selection set's bound in, with `shift` list wrappers applied.
    fn merge_shifted(&mut self, other: Self, shift: usize) {
        for (exponent, coefficient) in other.coefficients.into_iter().enumerate() {
            self.add(exponent + shift, coefficient);
        }
        self.depth = self.depth.max(other.depth);
    }
}

struct StaticAnalyzer<'a, 'document, 'source> {
    schema: &'a Schema,
    document: &'document ast::Document<'source>,
    work: u64,
    breadth: usize,
}

impl<'a, 'document, 'source> StaticAnalyzer<'a, 'document, 'source> {
    fn analyze_selection<I>(
        &mut self,
        items: I,
        scope: &Arc<str>,
        depth: usize,
        active_fragments: &mut SmallVec<[&'source str; 8]>,
        keys: &mut SmallVec<[&'source str; 16]>,
    ) -> Result<StaticBound, ()>
    where
        I: IntoIterator<Item = &'document ast::Selection<'source>>,
    {
        let mut bound = StaticBound {
            coefficients: SmallVec::new(),
            depth,
        };
        for selection in items {
            self.work = self.work.saturating_add(1);
            if self.work > MAX_ANALYSIS_WORK {
                return Err(());
            }

            match selection {
                ast::Selection::Field(field) => {
                    let response_key = field.response_key();
                    if !keys
                        .iter()
                        .any(|known| crate::types::names_eq(known, response_key))
                    {
                        keys.push(response_key);
                    }
                    // Every field occurrence is charged; the exact analysis merges duplicates, so
                    // charging each one can only over-estimate.
                    bound.add(0, u64::from(FIELD_COST));

                    // Any estimator may read argument values supplied by the request, whether or
                    // not the field has a selection set, so its presence disables the static
                    // bound for the whole operation.
                    let definition = field_definition_on(self.schema.get_type(scope), field.name);
                    if definition.is_some_and(|definition| definition.complexity.is_some()) {
                        return Err(());
                    }
                    let Some(selection_set) = &field.selection_set else {
                        continue;
                    };
                    let return_type = match definition {
                        Some(definition) => Cow::Borrowed(&definition.ty),
                        None => match meta_field_type(field.name) {
                            Some(ty) => ty,
                            // Same as the exact analysis: an unknown field is charged its base
                            // cost and not descended into.
                            None => continue,
                        },
                    };
                    let shift = list_depth(&return_type);
                    let named_type = return_type.named_type().clone();
                    let mut child_keys = SmallVec::new();
                    let inner = self.analyze_selection(
                        selection_set.items.iter(),
                        &named_type,
                        depth.saturating_add(1),
                        active_fragments,
                        &mut child_keys,
                    )?;
                    self.breadth = self.breadth.max(distinct_keys(&child_keys));
                    bound.merge_shifted(inner, shift);
                }
                ast::Selection::FragmentSpread(spread) => {
                    let Some(fragment) = self.document.fragment(spread.name) else {
                        return Err(());
                    };
                    if active_fragments.contains(&spread.name) {
                        continue;
                    }
                    if active_fragments.len() >= MAX_FRAGMENT_DEPTH {
                        return Err(());
                    }
                    // Resolve applicability exactly as the per-request analyzer does. A fragment
                    // that cannot apply is not charged; narrowing an abstract condition against an
                    // object parent must land on the object scope so its estimators are seen.
                    let Some(condition) =
                        fragment_scope(self.schema, fragment.type_condition, scope)
                    else {
                        continue;
                    };
                    active_fragments.push(spread.name);
                    let inner = self.analyze_selection(
                        fragment.selection_set.items.iter(),
                        &condition,
                        depth,
                        active_fragments,
                        keys,
                    );
                    active_fragments.pop();
                    bound.merge_shifted(inner?, 0);
                }
                ast::Selection::InlineFragment(fragment) => {
                    let condition = match fragment.type_condition {
                        Some(condition) => match fragment_scope(self.schema, condition, scope) {
                            Some(condition) => condition,
                            None => continue,
                        },
                        None => Arc::clone(scope),
                    };
                    let inner = self.analyze_selection(
                        fragment.selection_set.items.iter(),
                        &condition,
                        depth,
                        active_fragments,
                        keys,
                    )?;
                    bound.merge_shifted(inner, 0);
                }
            }
        }
        self.breadth = self.breadth.max(distinct_keys(keys));
        Ok(bound)
    }
}

/// The base cost execution charges for a field with no estimator.
///
/// `execute_operation` always analyses with `field_cost: 1`; keeping the constant named here
/// avoids silently diverging if that ever changes.
const FIELD_COST: u32 = 1;

fn distinct_keys(keys: &[&str]) -> usize {
    let mut distinct: SmallVec<[&str; 16]> = SmallVec::new();
    for key in keys {
        if !distinct
            .iter()
            .any(|known| crate::types::names_eq(known, key))
        {
            distinct.push(key);
        }
    }
    distinct.len()
}

/// The number of list wrappers around a type, which is the exponent of its list multiplier.
fn list_depth(ty: &TypeRef) -> usize {
    let mut depth = 0usize;
    let mut current = ty;
    loop {
        match current {
            TypeRef::NonNull(inner) => current = inner,
            TypeRef::List(inner) => {
                depth += 1;
                current = inner;
            }
            TypeRef::Named(_) => break,
        }
    }
    depth
}

/// The number of distinct response keys in one collected selection set.
///
/// `collected` keeps one entry per (response key, fragment scope) so cost accounting stays
/// conservative, but breadth counts response keys: a field selected again through a narrower
/// fragment does not make the set wider.
fn distinct_response_keys(fields: &[CollectedField<'_, '_>]) -> usize {
    let mut small: SmallVec<[&str; 16]> = SmallVec::new();
    let mut large: Option<FxHashSet<&str>> = None;
    for field in fields {
        if let Some(large) = &mut large {
            large.insert(field.response_key);
            continue;
        }
        if small.contains(&field.response_key) {
            continue;
        }
        small.push(field.response_key);
        if small.len() > 16 {
            large = Some(small.iter().copied().collect());
        }
    }
    large.map_or(small.len(), |large| large.len())
}

/// The response-key index for one collected selection set.
///
/// Selection sets are small, so the common case scans the collected list directly and never
/// allocates a hash map. Only a document with many distinct response keys pays for hashing.
struct FieldIndex<'source> {
    map: Option<FxHashMap<&'source str, SmallVec<[usize; 1]>>>,
}

impl<'source> FieldIndex<'source> {
    fn new() -> Self {
        Self { map: None }
    }
}

fn merge_field<'source, 'document>(
    output: &mut CollectedFields<'source, 'document>,
    index: &mut FieldIndex<'source>,
    field: &'document ast::Field<'source>,
    scope: &Arc<str>,
) {
    let response_key = field.response_key();
    if let Some(existing) = find_entry(output, index, response_key, scope) {
        // The specification merges field nodes with the same response key and the same parent
        // scope; their sub-selections are collected once.
        if let Some(selection_set) = &field.selection_set {
            output[existing]
                .selections
                .extend(selection_set.items.iter());
        }
        return;
    }
    // The same response key selected through a different, overlapping fragment scope is kept as a
    // separate accounting entry. The executor still resolves it once; charging both scopes is
    // deliberately conservative and prevents a narrow scope from hiding expensive fields that
    // only the other scope can see.
    push_entry(
        output,
        index,
        CollectedField {
            response_key,
            scope: Arc::clone(scope),
            node: field,
            selections: field
                .selection_set
                .as_ref()
                .map(|selection_set| selection_set.items.iter().collect())
                .unwrap_or_default(),
        },
    );
}

fn merge_all<'source, 'document>(
    output: &mut CollectedFields<'source, 'document>,
    index: &mut FieldIndex<'source>,
    fields: &[CollectedField<'source, 'document>],
) {
    for field in fields {
        // Re-run the scope-aware merge for the cached fragment's fields.
        match find_entry(output, index, field.response_key, &field.scope) {
            Some(existing) => output[existing]
                .selections
                .extend(field.selections.iter().copied()),
            None => push_entry(output, index, field.clone()),
        }
    }
}

fn find_entry<'source, 'document>(
    output: &CollectedFields<'source, 'document>,
    index: &FieldIndex<'source>,
    response_key: &str,
    scope: &str,
) -> Option<usize> {
    match &index.map {
        Some(map) => map.get(response_key).and_then(|positions| {
            positions
                .iter()
                .copied()
                .find(|position| output[*position].scope.as_ref() == scope)
        }),
        None => output.iter().position(|collected| {
            collected.response_key == response_key && collected.scope.as_ref() == scope
        }),
    }
}

fn push_entry<'source, 'document>(
    output: &mut CollectedFields<'source, 'document>,
    index: &mut FieldIndex<'source>,
    entry: CollectedField<'source, 'document>,
) {
    let position = output.len();
    let response_key = entry.response_key;
    output.push(entry);
    match &mut index.map {
        Some(map) => map.entry(response_key).or_default().push(position),
        None if output.len() > LINEAR_INDEX_LIMIT => {
            let mut map: FxHashMap<&'source str, SmallVec<[usize; 1]>> = FxHashMap::default();
            for (position, collected) in output.iter().enumerate() {
                map.entry(collected.response_key)
                    .or_default()
                    .push(position);
            }
            index.map = Some(map);
        }
        None => {}
    }
}

fn directive_if(directive: &ast::Directive<'_>, variables: &Object) -> Option<bool> {
    match &directive.argument("if")?.value {
        ast::Value::Boolean(value) => Some(*value),
        ast::Value::Variable(name) => variables.get(name).and_then(Value::as_bool),
        _ => None,
    }
}

/// The type a fragment's selections apply to, or `None` when it can never apply.
fn fragment_scope(schema: &Schema, condition: &str, parent: &Arc<str>) -> Option<Arc<str>> {
    if condition == parent.as_ref() {
        return Some(Arc::clone(parent));
    }

    let Some(condition_type) = schema.get_type(condition) else {
        // An unknown condition is a validation error; keep the enclosing scope.
        return Some(Arc::clone(parent));
    };
    let parent_type = schema.get_type(parent);

    match condition_type {
        Type::Object(_) => {
            if parent_type.is_some_and(|ty| ty.kind() == TypeKind::Object) {
                // Two distinct object types never overlap.
                None
            } else if schema.is_possible_type(parent, condition) {
                Some(Arc::from(condition))
            } else {
                None
            }
        }
        Type::Interface(_) | Type::Union(_) => {
            if parent_type.is_some_and(|ty| ty.kind() == TypeKind::Object) {
                if schema.is_possible_type(condition, parent) {
                    Some(Arc::clone(parent))
                } else {
                    None
                }
            } else {
                Some(Arc::from(condition))
            }
        }
        _ => None,
    }
}

/// Look a field up on a type that is already resolved.
fn field_definition_on<'t>(parent: Option<&'t Type>, name: &str) -> Option<&'t Field> {
    match parent? {
        Type::Object(object) => object.get_field(name),
        Type::Interface(interface) => interface.get_field(name),
        _ => None,
    }
}

/// The return type of a specification meta-field, which has no schema definition.
fn meta_field_type(name: &str) -> Option<Cow<'_, TypeRef>> {
    match name {
        "__typename" => None,
        "__schema" => Some(Cow::Owned(TypeRef::named("__Schema").non_null())),
        "__type" => Some(Cow::Owned(TypeRef::named("__Type"))),
        _ => None,
    }
}

/// The multiplier contributed by every list wrapper around a type.
fn list_multiplier(ty: &TypeRef, factor: u32) -> u32 {
    let mut multiplier = 1u32;
    let mut current = ty;
    loop {
        match current {
            TypeRef::NonNull(inner) => current = inner,
            TypeRef::List(inner) => {
                multiplier = multiplier.saturating_mul(factor);
                current = inner;
            }
            TypeRef::Named(_) => break,
        }
    }
    multiplier
}