fraiseql-core 2.19.0

Core execution engine for FraiseQL v2 - Compiled GraphQL over SQL
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
//! Argument-**value** validation for a root field — GraphQL § 5.6.1 (*Values of
//! Correct Type*), § 5.8.5 (*All Variable Usages Are Allowed*) and § 6.1.2
//! (*`CoerceVariableValues`*).
//!
//! Its sibling next door ([`super::argument_validation`]) checks argument
//! *names*; this one checks that the value written against a name has that
//! name's type. Before it, nothing did — on the literal path and the variable
//! path alike — and the consequence was not a lenient server but a **wrong
//! answer**:
//!
//! ```graphql
//! { products(limit: "2") { sku } }     # 12 rows, exit 0, no `errors` array
//! ```
//!
//! `limit` and `offset` are read out of the merged argument map with
//! `as_u64()`. A `String`, a `Bool`, a `Float`, a negative number or one past
//! `u32` all answer `None` there, and `None` means *no clause was emitted* — so
//! a request that explicitly asked to be bounded came back unbounded (#1197).
//! Every other argument instead reached PostgreSQL, which answered with a
//! `Database` error whose message can carry a **stored value** back to an
//! unauthenticated caller.
//!
//! The read sites fail closed on their own now
//! ([`crate::runtime::coerce_pagination_arg`]); this
//! module is what turns "the engine refused to paginate" into a diagnostic that
//! names the argument, the type it declares, and the type the document wrote.
//!
//! # What this adjudicates, and what it deliberately does not
//!
//! Following [`crate::graphql::validate_selection_set`] and § 5.4.1's module:
//! **reject what the document positively contradicts, pass everything it cannot
//! adjudicate.** A mismatch is reported only when *both* sides are one of the
//! built-in scalars in [`Scalar`] — the ten whose value space is a property of
//! the spec rather than of a project's own scalar wiring.
//!
//! Outside that set, execution is unchanged:
//!
//! * **Custom scalars, input objects, lists and vectors.** A project may back any of these with any
//!   JSON shape, so a disagreement here is not evidence of a client mistake.
//! * **Nested input-object fields**, for the scalar check above. Only the value written *at* the
//!   argument is adjudicated as a scalar, not the keys inside a `where:` predicate. Those have
//!   their own surface and their own operators.
//!
//! # Enums are the exception, and were wrongly inside the exclusion (#1362)
//!
//! Enums sat in that first bullet until #1362, and the bullet's own rationale is
//! what makes it wrong for them. A custom scalar's value space *is* a project's
//! choice — `Email` can be backed by anything the project's SQL accepts. An
//! enum's is not: [`EnumDefinition::values`] enumerates it, exhaustively, in the
//! compiled schema, and introspection publishes the same list. So a value that
//! is not one of those members is not an undecidable disagreement; it is
//! positively contradicted by the schema, which is exactly the standard the
//! paragraph above sets.
//!
//! Nothing checked it. `find_enum` had three callers — the § 5.8.2 *name* check,
//! a `SortDirection` presence test and introspection's kind resolution — and
//! every consumer of `EnumDefinition::values` was a generator (the client
//! emitters, the OpenAPI schema), never a validator. `BANANA`, `"pending"` and
//! `42` all reached the resolver, on the literal path and the variable path
//! alike, against an argument the schema says has three members.
//!
//! Enum membership is therefore adjudicated, and **nested input-object fields
//! are walked for it** — unlike the scalar check, which stops at the argument.
//! It has to: the shape the defect was reported against is an enum *inside* an
//! input object, and a `where:` predicate reaches its enums the same way.
//!
//! [`EnumDefinition::values`]: crate::schema::EnumDefinition::values
//! * **Nullability.** An explicit `null` is accepted for every argument, including a non-null one.
//!   That is § 5.6.1's other half; it changes which *documents* are valid rather than which
//!   *answers* are correct, so it is not folded in here.
//! * **Mutations** are adjudicated in full, from the mutation chokepoint rather than from here —
//!   see [`validate_mutation_argument_values`]. A write's input object is a record the function
//!   binds field by field, so a built-in scalar inside one is as positively declared as one at the
//!   argument, and a key the input type does not declare is refused (#1528).
//!
//! # Variable *values* are the half a spec-shaped fix would miss
//!
//! § 5.8.5 compares a variable's **declared type** against the argument's, which
//! catches `query($n: String!) { products(limit: $n) }`. It says nothing about
//! `query($n: Int!)` supplied with `{"n": "2"}` — the declaration is impeccable
//! and the *value* is wrong. That document returned the whole table too, so
//! [`validate_variable_values`] checks supplied values against their own
//! declarations (§ 6.1.2), including the case where a non-null variable is not
//! supplied at all: that also dropped its argument and widened the result.

use serde_json::Value;

use crate::{
    error::{FraiseQLError, Result},
    graphql::{
        types::{GraphQLArgument, VariableDefinition},
        value_json,
    },
    schema::{ArgumentDefinition, CompiledSchema, EnumDefinition, FieldType},
};

/// A built-in scalar whose value space this module is willing to adjudicate.
///
/// Membership is the whole leniency policy: a type that maps to `None` on both
/// constructors below is passed through untouched, because a project can back
/// it with any JSON shape and a disagreement would not be evidence of a client
/// mistake.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Scalar {
    Int,
    Float,
    String,
    Boolean,
    Id,
    Uuid,
    DateTime,
    Date,
    Time,
    Decimal,
}

impl Scalar {
    /// The scalar an argument's compiled type adjudicates as, or `None` for
    /// everything this module leaves alone.
    const fn from_field_type(field_type: &FieldType) -> Option<Self> {
        match field_type {
            FieldType::Int => Some(Self::Int),
            FieldType::Float => Some(Self::Float),
            FieldType::String => Some(Self::String),
            FieldType::Boolean => Some(Self::Boolean),
            FieldType::Id => Some(Self::Id),
            FieldType::Uuid => Some(Self::Uuid),
            FieldType::DateTime => Some(Self::DateTime),
            FieldType::Date => Some(Self::Date),
            FieldType::Time => Some(Self::Time),
            FieldType::Decimal => Some(Self::Decimal),
            _ => None,
        }
    }

    /// The scalar a *declared variable type name* adjudicates as.
    ///
    /// A name outside this set is a project's own scalar, an enum or an input
    /// object, and is not adjudicated — see the module header.
    fn from_type_name(name: &str) -> Option<Self> {
        match name {
            "Int" => Some(Self::Int),
            "Float" => Some(Self::Float),
            "String" => Some(Self::String),
            "Boolean" => Some(Self::Boolean),
            "ID" => Some(Self::Id),
            "UUID" => Some(Self::Uuid),
            "DateTime" => Some(Self::DateTime),
            "Date" => Some(Self::Date),
            "Time" => Some(Self::Time),
            "Decimal" => Some(Self::Decimal),
            _ => None,
        }
    }

    /// The name this scalar publishes, for error messages.
    const fn name(self) -> &'static str {
        match self {
            Self::Int => "Int",
            Self::Float => "Float",
            Self::String => "String",
            Self::Boolean => "Boolean",
            Self::Id => "ID",
            Self::Uuid => "UUID",
            Self::DateTime => "DateTime",
            Self::Date => "Date",
            Self::Time => "Time",
            Self::Decimal => "Decimal",
        }
    }

    /// Why `value` does not belong to this scalar, phrased for the client, or
    /// `None` when it does belong.
    ///
    /// Separate from [`Self::accepts`] so an integer that is merely too large
    /// does not read as "you wrote an Int where an Int was expected" — the
    /// message that first came out of `limit: 99999999999999`.
    fn rejection(self, value: &Value) -> Option<String> {
        if self.accepts(value) {
            return None;
        }
        if self == Self::Int && value.is_i64() {
            return Some(format!("an Int outside the 32-bit range ({}..={})", i32::MIN, i32::MAX));
        }
        if self == Self::Uuid && value.is_string() {
            return Some("a String that is not a UUID".to_string());
        }
        if self == Self::Decimal && value.is_number() {
            return Some(
                "a number an f64 had already rounded: write a Decimal's digits as a string"
                    .to_string(),
            );
        }
        Some(match json_shape(value) {
            shape @ ("a list" | "an object") => shape.to_string(),
            "Int" => "an Int value".to_string(),
            shape => format!("a {shape} value"),
        })
    }

    /// Does `value` belong to this scalar's value space?
    ///
    /// `null` belongs to every one of them: nullability is not adjudicated here
    /// (module header).
    fn accepts(self, value: &Value) -> bool {
        if value.is_null() {
            return true;
        }
        match self {
            // § 3.5.1: Int is 32-bit signed, and a Float literal is not an Int
            // even when its fractional part is zero. The range half is
            // load-bearing rather than pedantic — `limit: 99999999999999`
            // overflowed `u32` at the read site and dropped the clause.
            Self::Int => value.as_i64().is_some_and(|v| i32::try_from(v).is_ok()),
            Self::Float => value.is_number(),
            Self::String | Self::DateTime | Self::Date | Self::Time => value.is_string(),
            // A UUID's value space is fully specified, like an enum's (#1362): a string that
            // does not parse as one is contradicted by the type, not a project's choice. It
            // reached PostgreSQL as a cast error that quotes the value (#1528).
            Self::Uuid => value.as_str().is_some_and(|s| uuid::Uuid::parse_str(s).is_ok()),
            Self::Boolean => value.is_boolean(),
            // § 3.5.5: ID serializes as a String but accepts an integer input.
            Self::Id => value.is_string() || value.as_i64().is_some(),
            // A Decimal travels as a string of its digits. An integer held exactly is an
            // ordinary way to write one; a number with a fraction or an exponent was
            // rounded to an `f64` before anything could read it.
            Self::Decimal => value.is_string() || value.is_i64() || value.is_u64(),
        }
    }

    /// May a variable declared as `self` be used where `location` is expected
    /// (§ 5.8.5)?
    ///
    /// Deliberately wider than the spec's `AreTypesCompatible`, which admits
    /// only identical named types: a client declaring `$id: String!` for a
    /// `UUID` argument is writing the type its code generator produced for a
    /// custom scalar, not making the mistake this rule exists to catch. What is
    /// refused is a declaration whose value space cannot supply the location's
    /// — `String!` at `Int`, which is exactly how the unbounded page arrived.
    fn usable_at(self, location: Self) -> bool {
        if self == location {
            return true;
        }
        matches!(
            (self, location),
            (Self::Int, Self::Float | Self::Decimal | Self::Id)
                | (
                    Self::String,
                    Self::Id
                        | Self::Uuid
                        | Self::DateTime
                        | Self::Date
                        | Self::Time
                        | Self::Decimal
                )
                | (Self::Id, Self::String | Self::Uuid)
                | (Self::Uuid, Self::String | Self::Id)
                | (Self::DateTime | Self::Date | Self::Time | Self::Decimal, Self::String)
        )
    }
}

/// The scalar a supplied JSON value looks like, for an error message that says
/// what arrived rather than echoing it.
fn json_shape(value: &Value) -> &'static str {
    match value {
        Value::Null => "null",
        Value::Bool(_) => "Boolean",
        Value::Number(n) => {
            if n.is_f64() {
                "Float"
            } else {
                "Int"
            }
        },
        Value::String(_) => "String",
        Value::Array(_) => "a list",
        Value::Object(_) => "an object",
    }
}

/// Check the value written at each of `provided` against the type `declared`
/// gives that argument (§ 5.6.1), and the declared type of each variable used
/// there against the same (§ 5.8.5).
///
/// `field_label` names the field the way a client reads a schema —
/// `Query.orders` — and `declared` is the field's published argument list
/// ([`QueryDefinition::graphql_arguments`](crate::schema::QueryDefinition::graphql_arguments)),
/// which is where the auto-wired `limit: Int` and `offset: Int` acquire a type.
/// An argument with no entry there is not adjudicated: the relay cursor window
/// and `nearest` are read by their own runners and are accepted by name alone.
///
/// # Errors
///
/// Returns [`FraiseQLError::Validation`] naming the field, the argument, the
/// type it declares and the type the document wrote. The offending value is
/// **not** quoted back — the shape is what the client needs, and a value in an
/// error message is how #1197's second half returned a stored row to its caller.
pub fn validate_argument_values(
    field_label: &str,
    declared: &[ArgumentDefinition],
    provided: &[GraphQLArgument],
    variable_defs: &[VariableDefinition],
) -> Result<()> {
    for arg in provided {
        let Some(def) = declared.iter().find(|d| d.name == arg.name) else {
            continue;
        };
        let Some(location) = Scalar::from_field_type(&def.arg_type) else {
            continue;
        };

        // An enum literal is a bare name that JSON has to carry as a string;
        // whether it belongs at a scalar argument is an enum question, not this
        // one.
        if arg.value_type == "enum" {
            continue;
        }

        let value = value_json::decode(&arg.value_json)?;

        if let Some(var_name) = value_json::variable_name(&value) {
            check_variable_usage(field_label, &arg.name, location, var_name, variable_defs)?;
        } else if let Some(reason) = location.rejection(&value) {
            return Err(FraiseQLError::Validation {
                message: format!(
                    "Argument `{}` on {field_label} has type `{}`, but the document wrote {reason}",
                    arg.name,
                    location.name(),
                ),
                path:    Some(arg.name.clone()),
            });
        }
    }
    Ok(())
}

/// § 5.8.5 for one argument: the variable used there must be declared at a type
/// whose values the argument can accept.
fn check_variable_usage(
    field_label: &str,
    arg_name: &str,
    location: Scalar,
    var_name: &str,
    variable_defs: &[VariableDefinition],
) -> Result<()> {
    // An undeclared reference is § 5.8.3's error, raised before this runs.
    let Some(def) = variable_defs.iter().find(|v| v.name == var_name) else {
        return Ok(());
    };
    // A list-typed variable at a scalar argument is a shape question, and § 3.11
    // lets a single value stand for a list, so the wrapper is not adjudicated.
    if def.var_type.list {
        return Ok(());
    }
    let Some(declared) = Scalar::from_type_name(&def.var_type.name) else {
        return Ok(());
    };
    if declared.usable_at(location) {
        return Ok(());
    }
    Err(FraiseQLError::Validation {
        message: format!(
            "Variable `${var_name}` is declared as `{}` but is used for argument `{arg_name}` on \
             {field_label}, which has type `{}`",
            def.var_type.name,
            location.name()
        ),
        path:    Some(arg_name.to_string()),
    })
}

/// Check each supplied variable against the type its operation declares, and
/// refuse a non-null variable that carries no value at all (§ 6.1.2).
///
/// This is the half § 5.8.5 cannot reach. `query($n: Int!) { products(limit:
/// $n) }` is a correct *usage* whatever `{"n": "2"}` does to it, and what it
/// did was return the whole table: the value failed `as_u64()` at the read site
/// and the `LIMIT` clause was never emitted. The same happened when `$n` was
/// declared `Int!` and simply not supplied.
///
/// A variable with a **default** and no supplied value is left alone: the
/// default is what applies, and it was written against the same declaration.
/// A *nullable* variable with no value is also left alone, deliberately — that
/// is what lets `limit: $limit` fall back to the query's compiled default
/// instead of forcing `LIMIT NULL`.
///
/// # Errors
///
/// Returns [`FraiseQLError::Validation`] naming the variable and its declared
/// type. As above, the supplied value is described, never quoted.
pub fn validate_variable_values(
    operation_name: Option<&str>,
    variable_defs: &[VariableDefinition],
    values: Option<&Value>,
) -> Result<()> {
    let supplied = values.and_then(Value::as_object);

    for def in variable_defs {
        let value = supplied.and_then(|map| map.get(&def.name));

        let Some(value) = value else {
            if !def.var_type.nullable && def.default_value.is_none() {
                return Err(FraiseQLError::Validation {
                    message: format!(
                        "Variable `${}` is declared `{}!`{} but no value was supplied",
                        def.name,
                        def.var_type.name,
                        operation_label(operation_name)
                    ),
                    path:    Some(def.name.clone()),
                });
            }
            continue;
        };

        if value.is_null() && !def.var_type.nullable {
            return Err(FraiseQLError::Validation {
                message: format!(
                    "Variable `${}` is declared `{}!`{} but was supplied as null",
                    def.name,
                    def.var_type.name,
                    operation_label(operation_name)
                ),
                path:    Some(def.name.clone()),
            });
        }

        // A list declaration carries its items' type, not the value's; § 3.11
        // also lets a bare value stand for a one-element list. Neither is
        // adjudicated here.
        if def.var_type.list {
            continue;
        }
        let Some(declared) = Scalar::from_type_name(&def.var_type.name) else {
            continue;
        };
        if let Some(reason) = declared.rejection(value) {
            return Err(FraiseQLError::Validation {
                message: format!(
                    "Variable `${}` is declared `{}`{} but was supplied {reason}",
                    def.name,
                    def.var_type.name,
                    operation_label(operation_name),
                ),
                path:    Some(def.name.clone()),
            });
        }
    }
    Ok(())
}

// ── Enum membership — § 5.6.1 and § 6.1.2 for the one kind the schema fully
// ── specifies (#1362) ────────────────────────────────────────────────────────

/// How deep the walk follows nested input objects before giving up.
///
/// The recursion is driven by the *value*, which is finite, so this is a stack
/// guard and not a termination argument: a self-referential input object like
/// `OrderWhereInput._and: [OrderWhereInput!]` recurses only as far as the client
/// actually nested. Matches `value_json`'s own literal-nesting cap, so a document
/// that parsed cannot be refused here for depth it was already allowed.
const MAX_WALK_DEPTH: usize = 32;

/// At most this many members are named in a refusal before it summarises.
const MAX_MEMBERS_LISTED: usize = 12;

/// Adjudicate the values written at a mutation's arguments, from a **resolved**
/// argument map: enum membership (#1362), built-in scalars at every depth, and the keys
/// of every input object (#1528).
///
/// This is the entry the mutation chokepoint uses, and the reason it takes a map
/// rather than a document's `[GraphQLArgument]`: `execute_mutation_impl` is where
/// every transport that writes converges, and REST, gRPC and MCP arrive there
/// with a JSON payload and no GraphQL document at all. Inline literals are
/// already merged into that same map (#719), so one call covers a literal, a
/// variable and a payload alike.
///
/// `provided` is the map arguments are read out of — the value under each
/// argument's own name. An argument with no entry is not adjudicated; whether it
/// was required is the mutation runner's question, asked a few lines later. A
/// `localized` argument or input field is skipped: its value is a locale map by the
/// time this runs, checked by its own strict pass (`localized_input`).
///
/// Wider than the read path's walk on purpose. A read's input objects are predicates
/// (`where:`) with their own operators and surface; a write's are records whose every
/// field is bound into the function, so a value of the wrong type there is a wrong
/// value in the database (or a cast error quoting it), and an undeclared key is data
/// the function was never written to receive.
///
/// # Errors
///
/// Returns [`FraiseQLError::Validation`] naming the path to the offending field
/// and, as the case may be, the members its enum declares, the scalar type it
/// declares, or that its input type does not declare the key.
pub fn validate_mutation_argument_values(
    schema: &CompiledSchema,
    field_label: &str,
    declared: &[ArgumentDefinition],
    provided: Option<&Value>,
) -> Result<()> {
    let Some(map) = provided.and_then(Value::as_object) else {
        return Ok(());
    };
    for arg in declared.iter().filter(|arg| !arg.localized) {
        let Some(value) = map.get(&arg.name) else {
            continue;
        };
        walk_field_type(schema, Rules::WRITE, field_label, &arg.name, &arg.arg_type, value, 0)?;
    }
    Ok(())
}

/// What a walk adjudicates besides a list's item nullability, which every walk does
/// (#1614).
#[derive(Debug, Clone, Copy)]
struct Rules {
    /// Enum membership.
    enums:   bool,
    /// Built-in scalars under input objects and lists, and undeclared input keys.
    write:   bool,
    /// The value is a document literal, where a `{"$var": …}` object is a variable
    /// reference: its value is adjudicated against the variable's own declaration
    /// ([`validate_enum_variable_values`]), so the walk leaves it (#1610). Anywhere else
    /// (a variable's value, a resolved map, a REST payload) such an object is data.
    literal: bool,
}

impl Rules {
    /// A read's **resolved** arguments: item nullability only. Enum membership is the
    /// document and variable walks' question, which can name the variable a value came
    /// from; a resolved value cannot.
    const LIST_ITEMS: Self = Self {
        enums:   false,
        write:   false,
        literal: false,
    };
    /// The read paths' document literals: enum membership (module header).
    const LITERAL: Self = Self {
        enums:   true,
        write:   false,
        literal: true,
    };
    /// The read paths' variable values: enum membership.
    const READ: Self = Self {
        enums:   true,
        write:   false,
        literal: false,
    };
    /// A mutation's arguments: everything (#1528).
    const WRITE: Self = Self {
        enums:   true,
        write:   true,
        literal: false,
    };

    /// Whether `value` is a variable reference this walk leaves to the variable's own check.
    fn leaves(self, value: &Value) -> bool {
        self.literal && value_json::variable_name(value).is_some()
    }
}

/// Adjudicate enum membership for the **literals** a document writes at a field's
/// arguments (#1362).
///
/// The read path's counterpart to [`validate_mutation_argument_values`], for enums only. A value
/// that is a variable *reference* is skipped here and adjudicated by
/// [`validate_enum_variable_values`] against its own declaration, so neither
/// check has to resolve the other's half and a reference cannot be mistaken for
/// an object whose single key happens to be the variable marker.
///
/// # Errors
///
/// Returns [`FraiseQLError::Validation`] as above.
pub fn validate_enum_argument_literals(
    schema: &CompiledSchema,
    field_label: &str,
    declared: &[ArgumentDefinition],
    provided: &[GraphQLArgument],
) -> Result<()> {
    for arg in provided {
        let Some(def) = declared.iter().find(|d| d.name == arg.name) else {
            continue;
        };
        let value = value_json::decode(&arg.value_json)?;
        if value_json::variable_name(&value).is_some() {
            continue;
        }
        walk_field_type(schema, Rules::LITERAL, field_label, &arg.name, &def.arg_type, &value, 0)?;
    }
    Ok(())
}

/// Adjudicate enum membership for supplied variable values against their own
/// declarations — § 6.1.2, for enums (#1362).
///
/// Kept separate from [`validate_variable_values`] rather than folded into it
/// because that function answers a question about built-in scalars and needs no
/// schema; this one cannot be asked without one. They are called together at
/// every site, so the pair is the check.
///
/// # Errors
///
/// Returns [`FraiseQLError::Validation`] naming the variable and the members its
/// enum declares.
pub fn validate_enum_variable_values(
    schema: &CompiledSchema,
    operation_name: Option<&str>,
    variable_defs: &[VariableDefinition],
    values: Option<&Value>,
) -> Result<()> {
    let Some(map) = values.and_then(Value::as_object) else {
        return Ok(());
    };
    for def in variable_defs {
        let Some(value) = map.get(&def.name) else {
            continue;
        };
        let subject = format!("Variable `${}`{}", def.name, operation_label(operation_name));
        walk_type_ref(schema, Rules::READ, &subject, "", &def.var_type.name, value, 0)?;
    }
    Ok(())
}

/// Refuse a `null` item at a `[T!]` position anywhere in a read's **resolved** arguments:
/// an argument's own list, or a list field of an input object under it (#1614).
///
/// Run on the map the read is answered from, after inline literals and variables are merged
/// and nested `$var` references substituted, by both producers of a
/// [`QueryMatch`](crate::runtime::QueryMatch) (the GraphQL matcher, and
/// `QueryMatch::with_client_arguments`, which every other transport takes a client's
/// arguments through) and by a subscription's argument resolution. `argument` looks one up
/// by name. So a null item
/// is refused however it was written, and whichever transport carried it: a `nin: [null, …]`
/// reached SQL as `NOT IN (NULL, …)`, which is never true, and answered with no rows.
///
/// `declared` is the field's published argument list
/// ([`QueryDefinition::graphql_arguments`](crate::schema::QueryDefinition::graphql_arguments)).
/// A localized argument holds a locale map, checked by its own pass.
///
/// A null item is this walk's only refusal, so an argument whose
/// value holds no array with a null in it is not walked: the walk's per-item paths and
/// input-type lookups, and `field_label`, are paid only by a request that could be refused.
///
/// # Errors
///
/// Returns [`FraiseQLError::Validation`] naming the field and the path to the null item.
pub fn validate_argument_list_items<'a>(
    schema: &CompiledSchema,
    field_label: impl Fn() -> String,
    declared: &[ArgumentDefinition],
    argument: impl Fn(&str) -> Option<&'a Value>,
) -> Result<()> {
    for arg in declared.iter().filter(|arg| !arg.localized) {
        let Some(value) = argument(&arg.name).filter(|value| holds_a_null_item(value, 0)) else {
            continue;
        };
        walk_field_type(
            schema,
            Rules::LIST_ITEMS,
            &field_label(),
            &arg.name,
            &arg.arg_type,
            value,
            0,
        )?;
    }
    Ok(())
}

/// Whether any array under `value` (`value` itself included) may hold a `null` item.
///
/// Past the walk's depth bound the answer is yes: the walk, which stops there too, decides.
fn holds_a_null_item(value: &Value, depth: usize) -> bool {
    if depth > MAX_WALK_DEPTH {
        return true;
    }
    match value {
        Value::Array(items) => {
            items.iter().any(|item| item.is_null() || holds_a_null_item(item, depth + 1))
        },
        Value::Object(fields) => fields.values().any(|field| holds_a_null_item(field, depth + 1)),
        _ => false,
    }
}

/// Walk a compiled [`FieldType`] against `value`, adjudicating every enum under it
/// (and, under [`Rules::WRITE`], every built-in scalar and input key).
fn walk_field_type(
    schema: &CompiledSchema,
    rules: Rules,
    subject: &str,
    path: &str,
    declared: &FieldType,
    value: &Value,
    depth: usize,
) -> Result<()> {
    if value.is_null() || depth > MAX_WALK_DEPTH || rules.leaves(value) {
        return Ok(());
    }
    match declared {
        FieldType::List {
            item,
            nullable_items,
        } => walk_list(subject, path, *nullable_items, value, depth, |v, p, d| {
            walk_field_type(schema, rules, subject, p, item, v, d)
        }),
        FieldType::Enum(name) if rules.enums => {
            check_membership(schema, subject, path, name, value)
        },
        FieldType::Enum(_) => Ok(()),
        // The compiler emits an input-type reference as `Object`, never `Input`
        // (`parse_field_type` has no `Input` variant), so both have to resolve
        // through the input registry — the same pairing `execute_mutation_impl`
        // makes when it decides whether an argument is a structured input.
        FieldType::Object(name) | FieldType::Input(name) => {
            walk_input_object(schema, rules, subject, path, name, value, depth)
        },
        other => match Scalar::from_field_type(other) {
            Some(scalar) if rules.write => check_scalar(subject, path, scalar, value),
            _ => Ok(()),
        },
    }
}

/// Walk a **written** GraphQL type reference — the form an input field and a
/// variable declaration carry — against `value`.
///
/// Input fields store their type as a string (`"[OrderStatus!]"`), not a
/// [`FieldType`], so the wrappers are peeled here rather than matched.
fn walk_type_ref(
    schema: &CompiledSchema,
    rules: Rules,
    subject: &str,
    path: &str,
    declared: &str,
    value: &Value,
    depth: usize,
) -> Result<()> {
    if depth > MAX_WALK_DEPTH || rules.leaves(value) {
        return Ok(());
    }
    let declared = declared.trim();
    // `!` before `[`: `[X]!` peels to `[X]` and then to `X`, and `[X!]` to `X!`
    // to `X`. Peeling brackets first would leave a stray `!` on the inner name.
    if let Some(inner) = declared.strip_suffix('!') {
        return walk_type_ref(schema, rules, subject, path, inner, value, depth);
    }
    if let Some(inner) = declared.strip_prefix('[').and_then(|s| s.strip_suffix(']')) {
        let nullable_items = !inner.trim_end().ends_with('!');
        return walk_list(subject, path, nullable_items, value, depth, |v, p, d| {
            walk_type_ref(schema, rules, subject, p, inner, v, d)
        });
    }
    if value.is_null() {
        return Ok(());
    }
    if schema.find_enum(declared).is_some() {
        if !rules.enums {
            return Ok(());
        }
        return check_membership(schema, subject, path, declared, value);
    }
    if let (true, Some(scalar)) = (rules.write, Scalar::from_type_name(declared)) {
        return check_scalar(subject, path, scalar, value);
    }
    walk_input_object(schema, rules, subject, path, declared, value, depth)
}

/// Apply `walk` to each element of a list value, refusing a `null` element of a list whose
/// items are non-null (`[T!]`, § 3.11 input coercion, #1614).
///
/// A value that is not an array is walked as a single element rather than
/// skipped: § 3.11 lets a bare value stand for a one-element list, and that
/// coercion is how `where: {status: {in: PENDING}}` is written in practice. A
/// list declaration must not become a hole an unchecked enum fits through.
fn walk_list(
    subject: &str,
    path: &str,
    nullable_items: bool,
    value: &Value,
    depth: usize,
    mut walk: impl FnMut(&Value, &str, usize) -> Result<()>,
) -> Result<()> {
    match value.as_array() {
        Some(items) => {
            for (index, item) in items.iter().enumerate() {
                let at = format!("{path}[{index}]");
                if item.is_null() && !nullable_items {
                    return Err(FraiseQLError::Validation {
                        message: format!(
                            "{subject} at `{at}` is null, but the list's items are non-null"
                        ),
                        path:    Some(at),
                    });
                }
                walk(item, &at, depth + 1)?;
            }
            Ok(())
        },
        None => walk(value, path, depth + 1),
    }
}

/// Walk the fields of a declared input object, if `name` is one.
///
/// A name that is not a registered input object resolves to nothing and is
/// passed through: a custom scalar, an output object or a type this schema does
/// not declare is not this check's business.
fn walk_input_object(
    schema: &CompiledSchema,
    rules: Rules,
    subject: &str,
    path: &str,
    name: &str,
    value: &Value,
    depth: usize,
) -> Result<()> {
    let (Some(input_type), Some(object)) = (schema.find_input_type(name), value.as_object()) else {
        return Ok(());
    };
    let child_path = |key: &str| {
        if path.is_empty() {
            key.to_string()
        } else {
            format!("{path}.{key}")
        }
    };
    if rules.write {
        // § 5.6.2: every key must name a field the input type declares, under its surface
        // name or its stored one (the two spellings the loop below accepts).
        let declares = |key: &str| {
            input_type
                .fields
                .iter()
                .any(|f| f.name == key || schema.display_name(&f.name) == key)
        };
        if let Some(key) = object.keys().find(|key| !declares(key)) {
            let at = child_path(key);
            return Err(FraiseQLError::Validation {
                message: format!("{subject} at `{at}`: input type `{name}` declares no such field"),
                path:    Some(at),
            });
        }
    }
    for field in &input_type.fields {
        // A localized field holds a locale map by now, checked by its own pass.
        if rules.write && field.localized {
            continue;
        }
        // The client writes the *surface* name, which under `camelCase` differs
        // from the stored one. Both are accepted: `display_name` is what the
        // required-field check (#414) looks the value up by, and the canonical
        // name is what a payload arriving over REST or gRPC carries. Validating
        // only one of the two would leave the other transport's enums unchecked
        // — and a value present under either key is a value that reaches SQL.
        let surface = schema.display_name(&field.name);
        let value = object
            .get(surface.as_str())
            .or_else(|| (surface != field.name).then(|| object.get(&field.name)).flatten());
        let Some(value) = value else {
            continue;
        };
        let child = child_path(&surface);
        walk_type_ref(schema, rules, subject, &child, &field.field_type, value, depth + 1)?;
    }
    Ok(())
}

/// A built-in scalar at `path` must hold a value of its type (#1528).
fn check_scalar(subject: &str, path: &str, scalar: Scalar, value: &Value) -> Result<()> {
    match scalar.rejection(value) {
        None => Ok(()),
        // The value is described, never quoted back (#1197).
        Some(reason) => Err(FraiseQLError::Validation {
            message: format!(
                "{subject} at `{path}` has type `{}`, but the request wrote {reason}",
                scalar.name()
            ),
            path:    Some(path.to_string()),
        }),
    }
}

/// The adjudication itself: `value` must name a member of `enum_name`.
fn check_membership(
    schema: &CompiledSchema,
    subject: &str,
    path: &str,
    enum_name: &str,
    value: &Value,
) -> Result<()> {
    let Some(def) = schema.find_enum(enum_name) else {
        return Ok(());
    };
    // A GraphQL enum value is a bare name, which JSON carries as a string —
    // `value_json` encodes a literal `PENDING` and a variable-supplied
    // `"PENDING"` identically, which is what lets one check cover both paths.
    if let Some(written) = value.as_str() {
        if def.values.iter().any(|member| member.name == written) {
            return Ok(());
        }
    }
    let wrote = if value.is_string() {
        "a name that is not one of its members".to_string()
    } else {
        format!("{} , which is not a name at all", json_shape(value))
    };
    let at = if path.is_empty() {
        String::new()
    } else {
        format!(" at `{path}`")
    };
    Err(FraiseQLError::Validation {
        // The offending value is described, never quoted back — the same rule
        // the scalar half follows, and for the same reason (#1197). The members
        // are safe to name: introspection publishes exactly this list.
        message: format!(
            "{subject}{at} has enum type `{enum_name}`, but the document wrote {wrote}. \
             Valid members: {}",
            member_list(def)
        ),
        path:    (!path.is_empty()).then(|| path.to_string()),
    })
}

/// The members of `def`, capped so a large enum does not produce an unreadable
/// error.
fn member_list(def: &EnumDefinition) -> String {
    let total = def.values.len();
    let shown: Vec<&str> =
        def.values.iter().take(MAX_MEMBERS_LISTED).map(|v| v.name.as_str()).collect();
    if total > shown.len() {
        format!("{} (and {} more)", shown.join(", "), total - shown.len())
    } else {
        shown.join(", ")
    }
}

/// The " in operation ..." clause an error message carries, or nothing for an
/// anonymous operation.
fn operation_label(operation_name: Option<&str>) -> String {
    operation_name.map_or_else(String::new, |name| format!(" in operation `{name}`"))
}

#[cfg(test)]
#[path = "argument_value_validation_tests.rs"]
mod argument_value_validation_tests;