golem-schema 1.6.0

Golem schema and value model
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
// Copyright 2024-2026 Golem Cloud
//
// Licensed under the Golem Source License v1.1 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://license.golem.cloud/LICENSE
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! Structural well-formedness checks for a [`SchemaGraph`].

use crate::schema::graph::{RefResolutionError, SchemaGraph};
use crate::schema::metadata::TypeId;
use crate::schema::schema_type::{
    BinaryRestrictions, DiscriminatorRule, NumericRestrictionError, PathSpec, QuantitySpec,
    QuantityValue, SchemaType, TextRestrictions, UnionBranch, UnionSpec, UrlRestrictions,
};
use std::collections::HashSet;
use std::error::Error;
use std::fmt::{self, Display, Formatter};

/// All structural errors that can be raised by [`validate_graph`].
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum SchemaError {
    /// Validation requires an optional Cargo feature.
    UnsupportedFeature(&'static str),
    DuplicateTypeId(TypeId),
    DanglingRef(TypeId),
    /// A named reference whose alias chain is a pure cycle
    /// (`A -> B -> ... -> A`) that never bottoms out in a concrete type, so it
    /// can never resolve to a usable `SchemaType`.
    RecursiveAlias(TypeId),
    EmptyVariant,
    EmptyEnum,
    EmptyUnion,
    EmptyFlags,
    DuplicateFieldName(String),
    DuplicateVariantCase(String),
    DuplicateEnumCase(String),
    DuplicateFlagName(String),
    DuplicateUnionTag(String),
    MapKeyNotPrimitive,
    FixedListZeroLength,
    QuantityMinGreaterThanMax,
    QuantityMinUnitMismatch {
        base_unit: String,
        min_unit: String,
    },
    QuantityMaxUnitMismatch {
        base_unit: String,
        max_unit: String,
    },
    QuantityComparisonOverflow {
        base_unit: String,
    },
    UnionStringRuleOnNonStringBody {
        tag: String,
    },
    UnionFieldRuleOnNonRecordBody {
        tag: String,
    },
    UnionFieldEqualsLiteralOnNonStringField {
        tag: String,
        field_name: String,
    },
    UnionFieldRuleMissingField {
        tag: String,
        field_name: String,
    },
    UnionAmbiguousDiscriminators {
        tag_a: String,
        tag_b: String,
        reason: String,
    },
    UnionUnsatisfiableFieldAbsent {
        tag: String,
        field_name: String,
    },
    InvalidRegex {
        tag: String,
        regex: String,
        message: String,
    },
    InvalidTextRegex {
        regex: String,
        message: String,
    },
    TextLengthRangeInverted,
    BinaryByteRangeInverted,
    /// A numeric type's inline restrictions are not well-formed.
    InvalidNumericRestriction {
        error: NumericRestrictionError,
    },
    /// An `Option<X>` was declared where `X` is itself nullable on the
    /// canonical JSON wire (option-of-option, option-of-union-with-nullable-
    /// branch, option-of-ref-resolving-to-nullable). The canonical JSON
    /// encoding `null | inner` collapses `Some(None)` and `None`, so the
    /// nesting is rejected at construction time.
    NullableNesting {
        inner: String,
    },
}

impl Display for SchemaError {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        match self {
            SchemaError::UnsupportedFeature(feature) => {
                write!(f, "schema requires feature `{feature}`")
            }
            SchemaError::DuplicateTypeId(id) => write!(f, "duplicate type id `{id}`"),
            SchemaError::DanglingRef(id) => write!(f, "dangling type reference `{id}`"),
            SchemaError::RecursiveAlias(id) => {
                write!(
                    f,
                    "type reference `{id}` forms a reference cycle with no concrete type"
                )
            }
            SchemaError::EmptyVariant => write!(f, "variant has no cases"),
            SchemaError::EmptyEnum => write!(f, "enum has no cases"),
            SchemaError::EmptyUnion => write!(f, "union has no branches"),
            SchemaError::EmptyFlags => write!(f, "flags has no entries"),
            SchemaError::DuplicateFieldName(name) => write!(f, "duplicate field `{name}`"),
            SchemaError::DuplicateVariantCase(name) => {
                write!(f, "duplicate variant case `{name}`")
            }
            SchemaError::DuplicateEnumCase(name) => write!(f, "duplicate enum case `{name}`"),
            SchemaError::DuplicateFlagName(name) => write!(f, "duplicate flag `{name}`"),
            SchemaError::DuplicateUnionTag(tag) => write!(f, "duplicate union branch tag `{tag}`"),
            SchemaError::MapKeyNotPrimitive => {
                write!(f, "map key must be a primitive type")
            }
            SchemaError::FixedListZeroLength => write!(f, "fixed-list length must be > 0"),
            SchemaError::QuantityMinGreaterThanMax => {
                write!(f, "quantity min is greater than max")
            }
            SchemaError::QuantityMinUnitMismatch {
                base_unit,
                min_unit,
            } => write!(
                f,
                "quantity min unit mismatch: base `{base_unit}`, min `{min_unit}`"
            ),
            SchemaError::QuantityMaxUnitMismatch {
                base_unit,
                max_unit,
            } => write!(
                f,
                "quantity max unit mismatch: base `{base_unit}`, max `{max_unit}`"
            ),
            SchemaError::QuantityComparisonOverflow { base_unit } => write!(
                f,
                "quantity range comparison overflowed in base unit `{base_unit}`"
            ),
            SchemaError::UnionStringRuleOnNonStringBody { tag } => write!(
                f,
                "union branch `{tag}` uses a string-pattern rule but its body's canonical raw \
                 JSON representation is not a string"
            ),
            SchemaError::UnionFieldRuleOnNonRecordBody { tag } => write!(
                f,
                "union branch `{tag}` uses a field rule but body is not record-shaped"
            ),
            SchemaError::UnionFieldEqualsLiteralOnNonStringField { tag, field_name } => write!(
                f,
                "union branch `{tag}` references field `{field_name}` for a literal comparison \
                 but the field's canonical raw JSON representation is not a string"
            ),
            SchemaError::UnionFieldRuleMissingField { tag, field_name } => write!(
                f,
                "union branch `{tag}` references record field `{field_name}` that does not exist"
            ),
            SchemaError::UnionAmbiguousDiscriminators {
                tag_a,
                tag_b,
                reason,
            } => write!(
                f,
                "union branches `{tag_a}` and `{tag_b}` have overlapping discriminators ({reason})"
            ),
            SchemaError::UnionUnsatisfiableFieldAbsent { tag, field_name } => write!(
                f,
                "union branch `{tag}` uses field-absent on `{field_name}` but the record body \
                 declares that field"
            ),
            SchemaError::InvalidRegex {
                tag,
                regex,
                message,
            } => write!(
                f,
                "union branch `{tag}` regex `{regex}` failed to compile: {message}"
            ),
            SchemaError::InvalidTextRegex { regex, message } => {
                write!(f, "text regex `{regex}` failed to compile: {message}")
            }
            SchemaError::TextLengthRangeInverted => {
                write!(f, "text min-length is greater than max-length")
            }
            SchemaError::InvalidNumericRestriction { error } => {
                write!(f, "invalid numeric restriction: {error}")
            }
            SchemaError::BinaryByteRangeInverted => {
                write!(f, "binary min-bytes is greater than max-bytes")
            }
            SchemaError::NullableNesting { inner } => write!(
                f,
                "option<{inner}> is invalid because the inner type is also nullable; \
                 use a variant with explicit cases to distinguish absence from explicit none"
            ),
        }
    }
}

impl Error for SchemaError {}

/// Validate a [`SchemaGraph`] for structural well-formedness.
///
/// Returns the full list of collected errors. Ordering is deterministic:
/// errors are reported in the order they are discovered while walking the
/// graph.
pub fn validate_graph(graph: &SchemaGraph) -> Result<(), Vec<SchemaError>> {
    let mut errors = Vec::new();

    let mut seen_ids: HashSet<&TypeId> = HashSet::new();
    for def in &graph.defs {
        if !seen_ids.insert(&def.id) {
            errors.push(SchemaError::DuplicateTypeId(def.id.clone()));
        }
    }

    let known_ids: HashSet<TypeId> = graph.defs.iter().map(|d| d.id.clone()).collect();

    for def in &graph.defs {
        check_type(graph, &def.body, &known_ids, &mut errors);
    }
    check_type(graph, &graph.root, &known_ids, &mut errors);

    if errors.is_empty() {
        Ok(())
    } else {
        Err(errors)
    }
}

/// Validate a single [`SchemaType`] as a root against an existing graph's
/// definitions for structural well-formedness.
///
/// Unlike [`validate_graph`], this does not validate the graph's own
/// [`SchemaGraph::root`] or its definition bodies; only `ty` is walked, with
/// [`SchemaType::Ref`]s resolved against `graph.defs`. This is for callers (such
/// as the tool validator) that embed many bare `SchemaType` roots which share a
/// single definitions carrier whose own `root` is an unused placeholder.
///
/// Errors are returned in deterministic discovery order.
pub fn validate_root_type(graph: &SchemaGraph, ty: &SchemaType) -> Result<(), Vec<SchemaError>> {
    let known_ids: HashSet<TypeId> = graph.defs.iter().map(|d| d.id.clone()).collect();
    let mut errors = Vec::new();
    check_type(graph, ty, &known_ids, &mut errors);
    if errors.is_empty() {
        Ok(())
    } else {
        Err(errors)
    }
}

fn check_type(
    graph: &SchemaGraph,
    ty: &SchemaType,
    known: &HashSet<TypeId>,
    errors: &mut Vec<SchemaError>,
) {
    match ty {
        SchemaType::Ref { id, .. } => {
            if !known.contains(id) {
                errors.push(SchemaError::DanglingRef(id.clone()));
            } else {
                match graph.resolve_ref(ty) {
                    Ok(_) => {}
                    // The id exists, but its alias chain is a pure cycle that
                    // never resolves to a concrete type. A legitimate recursive
                    // type (whose cycle passes through a value-shrinking
                    // constructor such as `list`/`record`) resolves to that
                    // constructor at the top-level alias step and is unaffected.
                    Err(RefResolutionError::RecursiveRef(cycle_id)) => {
                        errors.push(SchemaError::RecursiveAlias(cycle_id));
                    }
                    // The id exists, but following its alias chain reaches a
                    // reference to a definition that is absent from the graph.
                    // Report the dangling target so a root alias chain ending in
                    // a missing definition is rejected at the chain's tail.
                    Err(RefResolutionError::DanglingRef(target)) => {
                        errors.push(SchemaError::DanglingRef(target));
                    }
                }
            }
        }

        SchemaType::Record { fields, .. } => {
            let mut seen: HashSet<&str> = HashSet::new();
            for field in fields {
                if !seen.insert(field.name.as_str()) {
                    errors.push(SchemaError::DuplicateFieldName(field.name.clone()));
                }
                check_type(graph, &field.body, known, errors);
            }
        }

        SchemaType::Variant { cases, .. } => {
            if cases.is_empty() {
                errors.push(SchemaError::EmptyVariant);
            }
            let mut seen: HashSet<&str> = HashSet::new();
            for case in cases {
                if !seen.insert(case.name.as_str()) {
                    errors.push(SchemaError::DuplicateVariantCase(case.name.clone()));
                }
                if let Some(p) = &case.payload {
                    check_type(graph, p, known, errors);
                }
            }
        }

        SchemaType::Enum { cases, .. } => {
            if cases.is_empty() {
                errors.push(SchemaError::EmptyEnum);
            }
            let mut seen: HashSet<&str> = HashSet::new();
            for case in cases {
                if !seen.insert(case.as_str()) {
                    errors.push(SchemaError::DuplicateEnumCase(case.clone()));
                }
            }
        }

        SchemaType::Flags { flags, .. } => {
            if flags.is_empty() {
                errors.push(SchemaError::EmptyFlags);
            }
            let mut seen: HashSet<&str> = HashSet::new();
            for flag in flags {
                if !seen.insert(flag.as_str()) {
                    errors.push(SchemaError::DuplicateFlagName(flag.clone()));
                }
            }
        }

        SchemaType::Tuple { elements, .. } => {
            for e in elements {
                check_type(graph, e, known, errors);
            }
        }
        SchemaType::List { element, .. } => check_type(graph, element, known, errors),
        SchemaType::FixedList {
            element, length, ..
        } => {
            if *length == 0 {
                errors.push(SchemaError::FixedListZeroLength);
            }
            check_type(graph, element, known, errors);
        }
        SchemaType::Map { key, value, .. } => {
            // A key that resolves to a concrete non-primitive type is rejected.
            // A key that does not resolve to a concrete type (a dangling
            // reference or a pure alias cycle) is *not* reported here: that
            // failure is reported by the `check_type(key, ...)` recursion below,
            // and a `MapKeyNotPrimitive` on top of it would be misleading cascade
            // noise.
            if let MapKeyKind::NonPrimitive = classify_map_key(graph, key) {
                errors.push(SchemaError::MapKeyNotPrimitive);
            }
            check_type(graph, key, known, errors);
            check_type(graph, value, known, errors);
        }
        SchemaType::Option { inner, .. } => {
            if is_nullable(graph, inner, &mut HashSet::new()) {
                errors.push(SchemaError::NullableNesting {
                    inner: describe_nullable(inner),
                });
            }
            check_type(graph, inner, known, errors);
        }
        SchemaType::Result { spec, .. } => {
            if let Some(t) = &spec.ok {
                check_type(graph, t, known, errors);
            }
            if let Some(t) = &spec.err {
                check_type(graph, t, known, errors);
            }
        }

        SchemaType::Quantity { spec, .. } => check_quantity(spec, errors),

        SchemaType::Text { restrictions, .. } => check_text_restrictions(restrictions, errors),
        SchemaType::Binary { restrictions, .. } => check_binary_restrictions(restrictions, errors),
        SchemaType::Path { spec, .. } => check_path_spec(spec, errors),
        SchemaType::Url { restrictions, .. } => check_url_spec(restrictions, errors),

        SchemaType::Union { spec, .. } => {
            validate_union(graph, spec, known, errors);
        }

        SchemaType::Future { inner, .. } => {
            if let Some(t) = inner {
                check_type(graph, t, known, errors);
            }
        }
        SchemaType::Stream { inner, .. } => {
            if let Some(t) = inner {
                check_type(graph, t, known, errors);
            }
        }

        SchemaType::S8 { restrictions, .. }
        | SchemaType::S16 { restrictions, .. }
        | SchemaType::S32 { restrictions, .. }
        | SchemaType::S64 { restrictions, .. }
        | SchemaType::U8 { restrictions, .. }
        | SchemaType::U16 { restrictions, .. }
        | SchemaType::U32 { restrictions, .. }
        | SchemaType::U64 { restrictions, .. }
        | SchemaType::F32 { restrictions, .. }
        | SchemaType::F64 { restrictions, .. } => {
            if let Some(restrictions) = restrictions {
                let repr = ty.numeric_repr().expect("numeric variant => numeric repr");
                if let Err(error) = restrictions.validate_for_repr(repr) {
                    errors.push(SchemaError::InvalidNumericRestriction { error });
                }
            }
        }

        SchemaType::Secret { spec, .. } => {
            check_type(graph, &spec.inner, known, errors);
        }

        SchemaType::Bool { .. }
        | SchemaType::Char { .. }
        | SchemaType::String { .. }
        | SchemaType::Uuid { .. }
        | SchemaType::Datetime { .. }
        | SchemaType::Duration { .. }
        | SchemaType::QuotaToken { .. }
        | SchemaType::PermissionCard { .. } => {}
    }
}

/// Classification of a map key type after resolving named references (with
/// cycle detection).
enum MapKeyKind {
    /// The key resolves to a primitive type and is valid.
    Primitive,
    /// The key resolves to a concrete non-primitive type (or a reference
    /// cycle, which can never be primitive) and is invalid.
    NonPrimitive,
    /// The key is (or resolves through) a dangling reference, so its
    /// primitiveness cannot be determined; the dangling reference is reported
    /// separately.
    Unresolved,
}

fn classify_map_key(graph: &SchemaGraph, ty: &SchemaType) -> MapKeyKind {
    let mut visited: HashSet<TypeId> = HashSet::new();
    let mut current = ty;
    loop {
        match current {
            SchemaType::Ref { id, .. } => {
                if !visited.insert(id.clone()) {
                    // A pure alias cycle never resolves to a concrete type, so
                    // its primitiveness is unknown. It is reported as a
                    // `RecursiveAlias` by the `check_type(key, ...)` recursion; a
                    // `MapKeyNotPrimitive` on top of that would be misleading
                    // cascade noise.
                    return MapKeyKind::Unresolved;
                }
                match graph.lookup(id) {
                    Some(def) => current = &def.body,
                    None => return MapKeyKind::Unresolved,
                }
            }
            other => {
                return if is_primitive_key(other) {
                    MapKeyKind::Primitive
                } else {
                    MapKeyKind::NonPrimitive
                };
            }
        }
    }
}

fn is_primitive_key(ty: &SchemaType) -> bool {
    matches!(
        ty,
        SchemaType::Bool { .. }
            | SchemaType::S8 { .. }
            | SchemaType::S16 { .. }
            | SchemaType::S32 { .. }
            | SchemaType::S64 { .. }
            | SchemaType::U8 { .. }
            | SchemaType::U16 { .. }
            | SchemaType::U32 { .. }
            | SchemaType::U64 { .. }
            | SchemaType::F32 { .. }
            | SchemaType::F64 { .. }
            | SchemaType::Char { .. }
            | SchemaType::String { .. }
    )
}

fn check_quantity(spec: &QuantitySpec, errors: &mut Vec<SchemaError>) {
    if let Some(min) = &spec.min
        && min.unit != spec.base_unit
    {
        errors.push(SchemaError::QuantityMinUnitMismatch {
            base_unit: spec.base_unit.clone(),
            min_unit: min.unit.clone(),
        });
    }
    if let Some(max) = &spec.max
        && max.unit != spec.base_unit
    {
        errors.push(SchemaError::QuantityMaxUnitMismatch {
            base_unit: spec.base_unit.clone(),
            max_unit: max.unit.clone(),
        });
    }

    if let (Some(min), Some(max)) = (&spec.min, &spec.max)
        && min.unit == spec.base_unit
        && max.unit == spec.base_unit
    {
        match quantity_le(min, max) {
            Some(true) => {}
            Some(false) => errors.push(SchemaError::QuantityMinGreaterThanMax),
            None => errors.push(SchemaError::QuantityComparisonOverflow {
                base_unit: spec.base_unit.clone(),
            }),
        }
    }
}

/// Compare two [`QuantityValue`]s with the same unit, treating each as
/// `mantissa * 10^(-scale)`. Returns `Some(true)` iff `a <= b`, `Some(false)`
/// iff `a > b`, and `None` if rescaling overflows.
fn quantity_le(a: &QuantityValue, b: &QuantityValue) -> Option<bool> {
    let common = a.scale.max(b.scale);
    let a_shift = (common - a.scale).max(0) as u32;
    let b_shift = (common - b.scale).max(0) as u32;

    let ten: i128 = 10;
    let a_factor = ten.checked_pow(a_shift)?;
    let b_factor = ten.checked_pow(b_shift)?;
    let a_canon = (a.mantissa as i128).checked_mul(a_factor)?;
    let b_canon = (b.mantissa as i128).checked_mul(b_factor)?;
    Some(a_canon <= b_canon)
}

fn check_text_restrictions(restrictions: &TextRestrictions, errors: &mut Vec<SchemaError>) {
    if let (Some(min), Some(max)) = (restrictions.min_length, restrictions.max_length)
        && min > max
    {
        errors.push(SchemaError::TextLengthRangeInverted);
    }
    #[cfg(not(feature = "regex"))]
    if restrictions.regex.is_some() {
        errors.push(SchemaError::UnsupportedFeature("regex"));
    }
    #[cfg(feature = "regex")]
    if let Some(regex) = &restrictions.regex
        && let Err(e) = regex::Regex::new(regex.as_str())
    {
        errors.push(SchemaError::InvalidTextRegex {
            regex: regex.clone(),
            message: e.to_string(),
        });
    }
}

fn check_binary_restrictions(restrictions: &BinaryRestrictions, errors: &mut Vec<SchemaError>) {
    if let (Some(min), Some(max)) = (restrictions.min_bytes, restrictions.max_bytes)
        && min > max
    {
        errors.push(SchemaError::BinaryByteRangeInverted);
    }
}

fn check_path_spec(_spec: &PathSpec, _errors: &mut Vec<SchemaError>) {
    // PathSpec has no regex today; nothing to validate beyond structural
    // shape.
}

fn check_url_spec(_spec: &UrlRestrictions, _errors: &mut Vec<SchemaError>) {
    // URL schema structure has no constraints requiring the URL parser.
}

fn validate_union(
    graph: &SchemaGraph,
    spec: &UnionSpec,
    known: &HashSet<TypeId>,
    errors: &mut Vec<SchemaError>,
) {
    if spec.branches.is_empty() {
        errors.push(SchemaError::EmptyUnion);
    }
    let mut seen: HashSet<&str> = HashSet::new();
    for branch in &spec.branches {
        if !seen.insert(branch.tag.as_str()) {
            errors.push(SchemaError::DuplicateUnionTag(branch.tag.clone()));
        }
        check_union_branch(graph, branch, errors);
        check_type(graph, &branch.body, known, errors);
    }

    // Discriminator ambiguity check.
    for i in 0..spec.branches.len() {
        for j in (i + 1)..spec.branches.len() {
            let a = &spec.branches[i];
            let b = &spec.branches[j];
            if let DiscriminatorPairClassification::Reject(reason) =
                classify_discriminator_pair(&a.discriminator, &b.discriminator)
            {
                errors.push(SchemaError::UnionAmbiguousDiscriminators {
                    tag_a: a.tag.clone(),
                    tag_b: b.tag.clone(),
                    reason,
                });
            }
        }
    }
}

fn check_union_branch(graph: &SchemaGraph, branch: &UnionBranch, errors: &mut Vec<SchemaError>) {
    let shape = resolved_shape(graph, &branch.body, &mut HashSet::new());
    // The branch body is a dangling/recursive ref: its shape is unknown, so any
    // shape-vs-discriminator mismatch would be misleading noise on top of the
    // unresolved-reference error `check_type` already reports. Body-shape-
    // independent problems (an invalid regex) are still checked below.
    let shape_known = !matches!(shape, BodyShape::Unresolved);
    match &branch.discriminator {
        DiscriminatorRule::Prefix { .. }
        | DiscriminatorRule::Suffix { .. }
        | DiscriminatorRule::Contains { .. } => {
            if shape_known && !matches!(shape, BodyShape::String) {
                errors.push(SchemaError::UnionStringRuleOnNonStringBody {
                    tag: branch.tag.clone(),
                });
            }
        }
        DiscriminatorRule::Regex { regex } => {
            if shape_known && !matches!(shape, BodyShape::String) {
                errors.push(SchemaError::UnionStringRuleOnNonStringBody {
                    tag: branch.tag.clone(),
                });
            }
            #[cfg(not(feature = "regex"))]
            {
                let _ = regex;
                errors.push(SchemaError::UnsupportedFeature("regex"));
            }
            #[cfg(feature = "regex")]
            if regex.is_empty() {
                errors.push(SchemaError::InvalidRegex {
                    tag: branch.tag.clone(),
                    regex: regex.clone(),
                    message: "regex must be non-empty".to_string(),
                });
            } else if let Err(e) = regex::Regex::new(regex.as_str()) {
                errors.push(SchemaError::InvalidRegex {
                    tag: branch.tag.clone(),
                    regex: regex.clone(),
                    message: e.to_string(),
                });
            }
        }
        DiscriminatorRule::FieldEquals(field_disc) => match shape {
            BodyShape::Record(fields) => {
                match fields.iter().find(|(n, _)| n == &field_disc.field_name) {
                    None => errors.push(SchemaError::UnionFieldRuleMissingField {
                        tag: branch.tag.clone(),
                        field_name: field_disc.field_name.clone(),
                    }),
                    Some((_, ty)) => {
                        let field_shape = resolved_shape(graph, ty, &mut HashSet::new());
                        if field_disc.literal.is_some()
                            && !matches!(field_shape, BodyShape::String | BodyShape::Unresolved)
                        {
                            errors.push(SchemaError::UnionFieldEqualsLiteralOnNonStringField {
                                tag: branch.tag.clone(),
                                field_name: field_disc.field_name.clone(),
                            });
                        }
                    }
                }
            }
            BodyShape::Unresolved => {}
            _ => errors.push(SchemaError::UnionFieldRuleOnNonRecordBody {
                tag: branch.tag.clone(),
            }),
        },
        DiscriminatorRule::FieldAbsent { field_name } => match shape {
            BodyShape::Record(fields) => {
                if fields.iter().any(|(n, _)| n == field_name) {
                    errors.push(SchemaError::UnionUnsatisfiableFieldAbsent {
                        tag: branch.tag.clone(),
                        field_name: field_name.clone(),
                    });
                }
            }
            BodyShape::Unresolved => {}
            _ => errors.push(SchemaError::UnionFieldRuleOnNonRecordBody {
                tag: branch.tag.clone(),
            }),
        },
    }
}

#[derive(Clone, Debug, PartialEq, Eq)]
enum DiscriminatorPairClassification {
    Reject(String),
    Disjoint,
    Indeterminate,
}

fn classify_discriminator_pair(
    a: &DiscriminatorRule,
    b: &DiscriminatorRule,
) -> DiscriminatorPairClassification {
    match (a, b) {
        (DiscriminatorRule::Prefix { prefix: pa }, DiscriminatorRule::Prefix { prefix: pb }) => {
            if pa.starts_with(pb.as_str()) || pb.starts_with(pa.as_str()) {
                DiscriminatorPairClassification::Reject(format!(
                    "prefix `{pa}` and prefix `{pb}` overlap"
                ))
            } else {
                DiscriminatorPairClassification::Disjoint
            }
        }
        (DiscriminatorRule::Suffix { suffix: sa }, DiscriminatorRule::Suffix { suffix: sb }) => {
            if sa.ends_with(sb.as_str()) || sb.ends_with(sa.as_str()) {
                DiscriminatorPairClassification::Reject(format!(
                    "suffix `{sa}` and suffix `{sb}` overlap"
                ))
            } else {
                DiscriminatorPairClassification::Disjoint
            }
        }
        (DiscriminatorRule::Prefix { prefix }, DiscriminatorRule::Suffix { suffix })
        | (DiscriminatorRule::Suffix { suffix }, DiscriminatorRule::Prefix { prefix }) => {
            DiscriminatorPairClassification::Reject(format!(
                "prefix `{prefix}` and suffix `{suffix}` overlap"
            ))
        }
        (DiscriminatorRule::Prefix { prefix }, DiscriminatorRule::Contains { substring })
        | (DiscriminatorRule::Contains { substring }, DiscriminatorRule::Prefix { prefix }) => {
            DiscriminatorPairClassification::Reject(format!(
                "prefix `{prefix}` and contains `{substring}` overlap"
            ))
        }
        (DiscriminatorRule::Suffix { suffix }, DiscriminatorRule::Contains { substring })
        | (DiscriminatorRule::Contains { substring }, DiscriminatorRule::Suffix { suffix }) => {
            DiscriminatorPairClassification::Reject(format!(
                "suffix `{suffix}` and contains `{substring}` overlap"
            ))
        }
        (
            DiscriminatorRule::Contains { substring: ca },
            DiscriminatorRule::Contains { substring: cb },
        ) => DiscriminatorPairClassification::Reject(format!(
            "contains `{ca}` and contains `{cb}` overlap"
        )),
        (DiscriminatorRule::Regex { regex: ra }, DiscriminatorRule::Regex { regex: rb }) => {
            if ra == rb {
                DiscriminatorPairClassification::Reject(format!("both branches share regex `{ra}`"))
            } else {
                DiscriminatorPairClassification::Indeterminate
            }
        }
        (
            DiscriminatorRule::Regex { .. },
            DiscriminatorRule::Prefix { .. }
            | DiscriminatorRule::Suffix { .. }
            | DiscriminatorRule::Contains { .. },
        )
        | (
            DiscriminatorRule::Prefix { .. }
            | DiscriminatorRule::Suffix { .. }
            | DiscriminatorRule::Contains { .. },
            DiscriminatorRule::Regex { .. },
        ) => DiscriminatorPairClassification::Indeterminate,
        (
            DiscriminatorRule::Prefix { .. }
            | DiscriminatorRule::Suffix { .. }
            | DiscriminatorRule::Contains { .. }
            | DiscriminatorRule::Regex { .. },
            DiscriminatorRule::FieldEquals(_) | DiscriminatorRule::FieldAbsent { .. },
        )
        | (
            DiscriminatorRule::FieldEquals(_) | DiscriminatorRule::FieldAbsent { .. },
            DiscriminatorRule::Prefix { .. }
            | DiscriminatorRule::Suffix { .. }
            | DiscriminatorRule::Contains { .. }
            | DiscriminatorRule::Regex { .. },
        ) => DiscriminatorPairClassification::Disjoint,
        (DiscriminatorRule::FieldEquals(fa), DiscriminatorRule::FieldEquals(fb)) => {
            if fa.field_name != fb.field_name {
                return DiscriminatorPairClassification::Reject(format!(
                    "field-equals on `{}` and `{}` can match the same object",
                    fa.field_name, fb.field_name
                ));
            }
            match (&fa.literal, &fb.literal) {
                (None, _) | (_, None) => DiscriminatorPairClassification::Reject(format!(
                    "field-equals on `{}` without literal overlaps another field-equals on the \
                     same field",
                    fa.field_name
                )),
                (Some(la), Some(lb)) if la == lb => {
                    DiscriminatorPairClassification::Reject(format!(
                        "two field-equals on `{}` share literal `{la}`",
                        fa.field_name
                    ))
                }
                _ => DiscriminatorPairClassification::Disjoint,
            }
        }
        (
            DiscriminatorRule::FieldAbsent { field_name: fa },
            DiscriminatorRule::FieldAbsent { field_name: fb },
        ) => DiscriminatorPairClassification::Reject(format!(
            "field-absent on `{fa}` and `{fb}` can match the same object"
        )),
        (
            DiscriminatorRule::FieldEquals(field_equals),
            DiscriminatorRule::FieldAbsent {
                field_name: field_absent,
            },
        )
        | (
            DiscriminatorRule::FieldAbsent {
                field_name: field_absent,
            },
            DiscriminatorRule::FieldEquals(field_equals),
        ) => {
            if field_equals.field_name == *field_absent {
                DiscriminatorPairClassification::Disjoint
            } else {
                DiscriminatorPairClassification::Reject(format!(
                    "field-equals on `{}` and field-absent on `{field_absent}` can match the same \
                     object",
                    field_equals.field_name
                ))
            }
        }
    }
}

/// Whether `ty` can be encoded as JSON `null` on the canonical wire.
///
/// True when `ty` is an `Option<_>`, a `Union` whose any branch body is
/// nullable, or a `Ref` resolving (after cycle-aware traversal) to a
/// nullable type. The traversal terminates on cycles by treating any
/// re-entered [`TypeId`] as non-nullable.
fn is_nullable(graph: &SchemaGraph, ty: &SchemaType, visited: &mut HashSet<TypeId>) -> bool {
    match ty {
        SchemaType::Option { .. } => true,
        SchemaType::Union { spec, .. } => spec
            .branches
            .iter()
            .any(|b| is_nullable(graph, &b.body, visited)),
        SchemaType::Ref { id, .. } => {
            if !visited.insert(id.clone()) {
                return false;
            }
            let result = match graph.lookup(id) {
                Some(def) => is_nullable(graph, &def.body, visited),
                None => false,
            };
            visited.remove(id);
            result
        }
        _ => false,
    }
}

/// Short textual description of a nullable type used in the
/// [`SchemaError::NullableNesting`] message.
fn describe_nullable(ty: &SchemaType) -> String {
    match ty {
        SchemaType::Option { .. } => "option<_>".to_string(),
        SchemaType::Union { .. } => "union".to_string(),
        SchemaType::Ref { id, .. } => format!("ref `{id}`"),
        _ => "nullable".to_string(),
    }
}

#[derive(Clone, Debug)]
enum BodyShape<'a> {
    String,
    Record(Vec<(String, &'a SchemaType)>),
    Other,
    /// The body is a [`SchemaType::Ref`] that does not resolve to a concrete
    /// type (a dangling reference or a pure alias cycle). The shape is unknown,
    /// so shape-dependent discriminator checks are skipped; the unresolved
    /// reference itself is reported separately by [`check_type`].
    Unresolved,
}

fn resolved_shape<'a>(
    graph: &'a SchemaGraph,
    ty: &'a SchemaType,
    visited: &mut HashSet<TypeId>,
) -> BodyShape<'a> {
    match ty {
        SchemaType::Ref { id, .. } => {
            if !visited.insert(id.clone()) {
                return BodyShape::Unresolved;
            }
            match graph.lookup(id) {
                Some(def) => resolved_shape(graph, &def.body, visited),
                None => BodyShape::Unresolved,
            }
        }
        SchemaType::String { .. } | SchemaType::Url { .. } | SchemaType::Path { .. } => {
            BodyShape::String
        }
        SchemaType::Record { fields, .. } => BodyShape::Record(
            fields
                .iter()
                .map(|f| (f.name.clone(), &f.body))
                .collect::<Vec<_>>(),
        ),
        _ => BodyShape::Other,
    }
}

#[cfg(test)]
mod discriminator_pair_tests {
    use super::{DiscriminatorPairClassification, classify_discriminator_pair};
    use crate::schema::schema_type::{DiscriminatorRule, FieldDiscriminator};
    use test_r::test;

    #[derive(Clone, Copy, Debug)]
    enum ExpectedClassification {
        Reject,
        Disjoint,
        Indeterminate,
    }

    struct ClassificationCase {
        name: &'static str,
        left: DiscriminatorRule,
        right: DiscriminatorRule,
        expected: ExpectedClassification,
    }

    fn prefix(value: &str) -> DiscriminatorRule {
        DiscriminatorRule::Prefix {
            prefix: value.to_string(),
        }
    }

    fn suffix(value: &str) -> DiscriminatorRule {
        DiscriminatorRule::Suffix {
            suffix: value.to_string(),
        }
    }

    fn contains(value: &str) -> DiscriminatorRule {
        DiscriminatorRule::Contains {
            substring: value.to_string(),
        }
    }

    fn regex(value: &str) -> DiscriminatorRule {
        DiscriminatorRule::Regex {
            regex: value.to_string(),
        }
    }

    fn field_equals(field_name: &str, literal: Option<&str>) -> DiscriminatorRule {
        DiscriminatorRule::FieldEquals(FieldDiscriminator {
            field_name: field_name.to_string(),
            literal: literal.map(str::to_string),
        })
    }

    fn field_absent(field_name: &str) -> DiscriminatorRule {
        DiscriminatorRule::FieldAbsent {
            field_name: field_name.to_string(),
        }
    }

    #[test]
    fn discriminator_pair_classification_matches_portable_matrix() {
        use ExpectedClassification::{Disjoint, Indeterminate, Reject};

        let cases = vec![
            ClassificationCase {
                name: "prefix_prefix_nested_reject",
                left: prefix("a"),
                right: prefix("ab"),
                expected: Reject,
            },
            ClassificationCase {
                name: "prefix_prefix_disjoint",
                left: prefix("a"),
                right: prefix("b"),
                expected: Disjoint,
            },
            ClassificationCase {
                name: "empty_prefix_prefix_reject",
                left: prefix(""),
                right: prefix("a"),
                expected: Reject,
            },
            ClassificationCase {
                name: "suffix_suffix_nested_reject",
                left: suffix("ing"),
                right: suffix("ng"),
                expected: Reject,
            },
            ClassificationCase {
                name: "suffix_suffix_disjoint",
                left: suffix("a"),
                right: suffix("b"),
                expected: Disjoint,
            },
            ClassificationCase {
                name: "empty_suffix_suffix_reject",
                left: suffix(""),
                right: suffix("a"),
                expected: Reject,
            },
            ClassificationCase {
                name: "prefix_suffix_reject",
                left: prefix("a"),
                right: suffix("b"),
                expected: Reject,
            },
            ClassificationCase {
                name: "prefix_contains_reject",
                left: prefix("a"),
                right: contains("b"),
                expected: Reject,
            },
            ClassificationCase {
                name: "suffix_contains_reject",
                left: suffix("a"),
                right: contains("b"),
                expected: Reject,
            },
            ClassificationCase {
                name: "contains_contains_reject",
                left: contains("a"),
                right: contains("b"),
                expected: Reject,
            },
            ClassificationCase {
                name: "regex_regex_identical_reject",
                left: regex("a.*"),
                right: regex("a.*"),
                expected: Reject,
            },
            ClassificationCase {
                name: "regex_regex_distinct_indeterminate",
                left: regex("a.*"),
                right: regex(".*a"),
                expected: Indeterminate,
            },
            ClassificationCase {
                name: "regex_prefix_indeterminate",
                left: regex("^a"),
                right: prefix("a"),
                expected: Indeterminate,
            },
            ClassificationCase {
                name: "regex_empty_prefix_indeterminate",
                left: regex("^a"),
                right: prefix(""),
                expected: Indeterminate,
            },
            ClassificationCase {
                name: "regex_suffix_indeterminate",
                left: regex("a$"),
                right: suffix("a"),
                expected: Indeterminate,
            },
            ClassificationCase {
                name: "regex_empty_suffix_indeterminate",
                left: regex("a$"),
                right: suffix(""),
                expected: Indeterminate,
            },
            ClassificationCase {
                name: "regex_contains_indeterminate",
                left: regex("a"),
                right: contains("a"),
                expected: Indeterminate,
            },
            ClassificationCase {
                name: "regex_empty_contains_indeterminate",
                left: regex("a"),
                right: contains(""),
                expected: Indeterminate,
            },
            ClassificationCase {
                name: "prefix_field_equals_disjoint",
                left: prefix("a"),
                right: field_equals("kind", Some("a")),
                expected: Disjoint,
            },
            ClassificationCase {
                name: "prefix_field_absent_disjoint",
                left: prefix("a"),
                right: field_absent("kind"),
                expected: Disjoint,
            },
            ClassificationCase {
                name: "suffix_field_equals_disjoint",
                left: suffix("a"),
                right: field_equals("kind", Some("a")),
                expected: Disjoint,
            },
            ClassificationCase {
                name: "suffix_field_absent_disjoint",
                left: suffix("a"),
                right: field_absent("kind"),
                expected: Disjoint,
            },
            ClassificationCase {
                name: "contains_field_equals_disjoint",
                left: contains("a"),
                right: field_equals("kind", Some("a")),
                expected: Disjoint,
            },
            ClassificationCase {
                name: "contains_field_absent_disjoint",
                left: contains("a"),
                right: field_absent("kind"),
                expected: Disjoint,
            },
            ClassificationCase {
                name: "regex_field_equals_disjoint",
                left: regex("a"),
                right: field_equals("kind", Some("a")),
                expected: Disjoint,
            },
            ClassificationCase {
                name: "regex_field_absent_disjoint",
                left: regex("a"),
                right: field_absent("kind"),
                expected: Disjoint,
            },
            ClassificationCase {
                name: "field_equals_same_field_different_literals_disjoint",
                left: field_equals("kind", Some("a")),
                right: field_equals("kind", Some("b")),
                expected: Disjoint,
            },
            ClassificationCase {
                name: "field_equals_same_field_same_literal_reject",
                left: field_equals("kind", Some("a")),
                right: field_equals("kind", Some("a")),
                expected: Reject,
            },
            ClassificationCase {
                name: "field_equals_same_field_one_literal_absent_reject",
                left: field_equals("kind", None),
                right: field_equals("kind", Some("a")),
                expected: Reject,
            },
            ClassificationCase {
                name: "field_equals_same_field_both_literals_absent_reject",
                left: field_equals("kind", None),
                right: field_equals("kind", None),
                expected: Reject,
            },
            ClassificationCase {
                name: "field_equals_different_fields_reject",
                left: field_equals("left", Some("a")),
                right: field_equals("right", Some("b")),
                expected: Reject,
            },
            ClassificationCase {
                name: "field_absent_same_field_reject",
                left: field_absent("kind"),
                right: field_absent("kind"),
                expected: Reject,
            },
            ClassificationCase {
                name: "field_absent_different_fields_reject",
                left: field_absent("left"),
                right: field_absent("right"),
                expected: Reject,
            },
            ClassificationCase {
                name: "field_equals_field_absent_same_field_disjoint",
                left: field_equals("kind", Some("a")),
                right: field_absent("kind"),
                expected: Disjoint,
            },
            ClassificationCase {
                name: "field_equals_field_absent_different_fields_reject",
                left: field_equals("left", Some("a")),
                right: field_absent("right"),
                expected: Reject,
            },
        ];

        for case in cases {
            assert_classification(
                case.name,
                "forward",
                classify_discriminator_pair(&case.left, &case.right),
                case.expected,
            );
            assert_classification(
                case.name,
                "reverse",
                classify_discriminator_pair(&case.right, &case.left),
                case.expected,
            );
        }
    }

    fn assert_classification(
        name: &str,
        order: &str,
        actual: DiscriminatorPairClassification,
        expected: ExpectedClassification,
    ) {
        let matches = matches!(
            (&actual, expected),
            (
                DiscriminatorPairClassification::Reject(_),
                ExpectedClassification::Reject
            ) | (
                DiscriminatorPairClassification::Disjoint,
                ExpectedClassification::Disjoint
            ) | (
                DiscriminatorPairClassification::Indeterminate,
                ExpectedClassification::Indeterminate
            )
        );
        assert!(
            matches,
            "{name} ({order}): expected {expected:?}, got {actual:?}"
        );
    }
}