drift 0.1.3

Library for comparing the compatibility of OpenAPI documents
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
// Copyright 2025 Oxide Computer Company

use std::fmt;

use openapiv3::{AdditionalProperties, ArrayType, ObjectType, ReferenceOr, Schema, SchemaData};

use crate::{
    ChangeClass, ChangeComparison, ChangeDetails,
    compare::Compare,
    context::{Contextual, ToContext},
    setops::SetCompare,
};

#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub(crate) enum SchemaComparison {
    Input,
    Output,
}

impl From<SchemaComparison> for ChangeComparison {
    fn from(value: SchemaComparison) -> Self {
        match value {
            SchemaComparison::Input => ChangeComparison::Input,
            SchemaComparison::Output => ChangeComparison::Output,
        }
    }
}

impl Compare {
    pub fn compare_schema_ref(
        &mut self,
        comparison: SchemaComparison,
        old_schema: Contextual<'_, &ReferenceOr<Schema>>,
        new_schema: Contextual<'_, &ReferenceOr<Schema>>,
    ) -> anyhow::Result<()> {
        let _ = self.compare_schema_ref_helper(false, comparison, old_schema, new_schema)?;
        Ok(())
    }

    fn compare_schema_ref_helper(
        &mut self,
        dry_run: bool,
        comparison: SchemaComparison,
        old_schema: Contextual<'_, &ReferenceOr<Schema>>,
        new_schema: Contextual<'_, &ReferenceOr<Schema>>,
    ) -> anyhow::Result<bool> {
        // Handle single-element wrappers: allOf/anyOf/oneOf with one item.
        // These are semantically equivalent to their inner type.
        //
        // An allOf wrapper is commonly added to include additional metadata
        // such as an additional description field.
        if let Some(result) =
            self.try_compare_flattened(dry_run, comparison, &old_schema, &new_schema)?
        {
            Ok(result)
        } else {
            // General path: resolve and compare.
            let (old_schema, old_context) = old_schema.contextual_resolve()?;
            let (new_schema, new_context) = new_schema.contextual_resolve()?;

            let old_schema = Contextual::new(old_context, old_schema.as_ref());
            let new_schema = Contextual::new(new_context, new_schema.as_ref());

            self.compare_schema(comparison, dry_run, old_schema, new_schema)
        }
    }

    /// Try to compare schemas by flattening single-element wrappers.
    ///
    /// Returns `Some(result)` if flattening was applicable, `None` to fall
    /// through to the general path.
    fn try_compare_flattened(
        &mut self,
        dry_run: bool,
        comparison: SchemaComparison,
        old_schema: &Contextual<'_, &ReferenceOr<Schema>>,
        new_schema: &Contextual<'_, &ReferenceOr<Schema>>,
    ) -> anyhow::Result<Option<bool>> {
        use SchemaRefKind::*;

        let old_kind = classify_schema_ref(old_schema.as_ref());
        let new_kind = classify_schema_ref(new_schema.as_ref());

        match (old_kind, new_kind) {
            (
                SingleElement {
                    inner: old_inner,
                    metadata: old_meta,
                },
                SingleElement {
                    inner: new_inner,
                    metadata: new_meta,
                },
            ) => {
                // Both old and new are single-element wrappers.
                if old_meta != new_meta {
                    self.push_change(
                        "schema metadata changed",
                        old_schema,
                        new_schema,
                        comparison.into(),
                        ChangeClass::Trivial,
                        ChangeDetails::Metadata,
                    );
                }
                let old_inner = old_schema.append_deref(old_inner, "0");
                let new_inner = new_schema.append_deref(new_inner, "0");
                Ok(Some(self.compare_schema_ref_helper(
                    dry_run, comparison, old_inner, new_inner,
                )?))
            }
            (
                SingleElement {
                    inner: old_inner,
                    metadata: old_meta,
                },
                BareRef | InlineType,
            ) => {
                // Old is a single-element wrapper, new is a bare ref or inline
                // type.
                //
                // A bare ref or inline type does not have metadata, so if the
                // old metadata is non-default, report a trivial change.
                if has_meaningful_metadata(old_meta) {
                    self.push_change(
                        "schema metadata removed",
                        old_schema,
                        new_schema,
                        comparison.into(),
                        ChangeClass::Trivial,
                        ChangeDetails::Metadata,
                    );
                }
                let old_inner = old_schema.append_deref(old_inner, "0");
                Ok(Some(self.compare_schema_ref_helper(
                    dry_run,
                    comparison,
                    old_inner,
                    new_schema.clone(),
                )?))
            }
            (
                BareRef | InlineType,
                SingleElement {
                    inner: new_inner,
                    metadata: new_meta,
                },
            ) => {
                // Old is a bare ref or inline type, new is a single-element
                // wrapper.
                //
                // A bare ref or inline type does not have metadata, so if the
                // new metadata is non-default, report a trivial change.
                if has_meaningful_metadata(new_meta) {
                    self.push_change(
                        "schema metadata added",
                        old_schema,
                        new_schema,
                        comparison.into(),
                        ChangeClass::Trivial,
                        ChangeDetails::Metadata,
                    );
                }
                let new_inner = new_schema.append_deref(new_inner, "0");
                Ok(Some(self.compare_schema_ref_helper(
                    dry_run,
                    comparison,
                    old_schema.clone(),
                    new_inner,
                )?))
            }
            (BareRef | InlineType | MultiElement, BareRef | InlineType | MultiElement)
            | (SingleElement { .. }, MultiElement)
            | (MultiElement, SingleElement { .. }) => {
                // No flattening applicable, so fall through to the general
                // comparison path.
                Ok(None)
            }
        }
    }

    fn compare_schema(
        &mut self,
        comparison: SchemaComparison,
        dry_run: bool,
        old_schema: Contextual<'_, &Schema>,
        new_schema: Contextual<'_, &Schema>,
    ) -> anyhow::Result<bool> {
        // We wait for both new and old to contain a cycle; this ensures that
        // we consider "unrolled" cycles properly. There is a possibility of
        // getting stuck in an A->B->A / B->A->B cycle... we can address that
        // should that construction arise.
        if old_schema.context().stack().contains_cycle()
            && new_schema.context().stack().contains_cycle()
        {
            return Ok(true);
        }

        // Return the cached compatibility of these schemas so that we don't
        // generate redundant notes.
        if let Some(equal) = self.visited.get(&(
            comparison,
            old_schema.context().stack().top.clone(),
            new_schema.context().stack().top.clone(),
        )) {
            return Ok(*equal);
        }

        // We expand structures to ensure we don't accidentally fail to examine
        // a field.
        let Schema {
            schema_data:
                SchemaData {
                    nullable: old_nullable,
                    read_only: old_read_only,
                    write_only: old_write_only,
                    deprecated: old_deprecated,
                    external_docs: old_external_docs,
                    example: old_example,
                    title: old_title,
                    description: old_description,
                    discriminator: old_discriminator,
                    default: old_default,
                    extensions: old_extensions,
                },
            schema_kind: old_schema_kind,
        } = old_schema.as_ref();
        let Schema {
            schema_data:
                SchemaData {
                    nullable: new_nullable,
                    read_only: new_read_only,
                    write_only: new_write_only,
                    deprecated: new_deprecated,
                    external_docs: new_external_docs,
                    example: new_example,
                    title: new_title,
                    description: new_description,
                    discriminator: new_discriminator,
                    default: new_default,
                    extensions: new_extensions,
                },
            schema_kind: new_schema_kind,
        } = new_schema.as_ref();

        // Examine properties that don't affect the serialized form.
        let metadata_equal = old_read_only == new_read_only
            && old_write_only == new_write_only
            && old_deprecated == new_deprecated
            && old_external_docs == new_external_docs
            && old_example == new_example
            && old_title == new_title
            && old_description == new_description
            && old_discriminator == new_discriminator
            && old_default == new_default
            && old_extensions == new_extensions;

        if !metadata_equal {
            let _ = self.schema_push_change(
                dry_run,
                "schema metadata changed".to_string(),
                &old_schema,
                &new_schema,
                comparison,
                ChangeClass::Trivial,
                ChangeDetails::Metadata,
            );
        }

        let nullable_equal = old_nullable == new_nullable;
        let schema_equal = self.compare_schema_kind(
            comparison,
            dry_run,
            Contextual::new(old_schema.context().clone(), old_schema_kind),
            Contextual::new(new_schema.context().clone(), new_schema_kind),
        )?;

        // Cache the result.
        self.visited.insert(
            (
                comparison,
                old_schema.context().stack().top.clone(),
                new_schema.context().stack().top.clone(),
            ),
            nullable_equal && schema_equal,
        );

        Ok(nullable_equal && schema_equal)
    }

    pub(crate) fn compare_schema_kind(
        &mut self,
        comparison: SchemaComparison,
        dry_run: bool,
        old_schema_kind: Contextual<'_, &openapiv3::SchemaKind>,
        new_schema_kind: Contextual<'_, &openapiv3::SchemaKind>,
    ) -> anyhow::Result<bool> {
        match (old_schema_kind.as_ref(), new_schema_kind.as_ref()) {
            (&openapiv3::SchemaKind::Type(old_type), &openapiv3::SchemaKind::Type(new_type)) => {
                self.compare_schema_type(
                    comparison,
                    dry_run,
                    old_schema_kind.subcomponent(old_type),
                    new_schema_kind.subcomponent(new_type),
                )
            }
            (
                openapiv3::SchemaKind::OneOf { one_of: old_one_of },
                openapiv3::SchemaKind::OneOf { one_of: new_one_of },
            ) => {
                let old_one_of = old_schema_kind.append_deref(old_one_of, "oneOf");
                let new_one_of = new_schema_kind.append_deref(new_one_of, "oneOf");
                self.compare_schema_type_one_of(comparison, dry_run, old_one_of, new_one_of)
            }
            (
                openapiv3::SchemaKind::AllOf { all_of: old_all_of },
                openapiv3::SchemaKind::AllOf { all_of: new_all_of },
            ) => {
                let old_all_of = old_schema_kind.append_deref(old_all_of, "allOf");
                let new_all_of = new_schema_kind.append_deref(new_all_of, "allOf");
                self.compare_schema_type_all_of(comparison, dry_run, old_all_of, new_all_of)
            }

            (
                openapiv3::SchemaKind::AnyOf { any_of: old_any_of },
                openapiv3::SchemaKind::AnyOf { any_of: new_any_of },
            ) => {
                if old_any_of != new_any_of {
                    self.schema_push_change(
                        dry_run,
                        "unhandled, 'anyOf' schema",
                        &old_schema_kind,
                        &new_schema_kind,
                        comparison,
                        ChangeClass::Unhandled,
                        ChangeDetails::UnknownDifference,
                    )
                } else {
                    Ok(true)
                }
            }
            (
                openapiv3::SchemaKind::Not { not: old_not },
                openapiv3::SchemaKind::Not { not: new_not },
            ) => {
                let old_not = old_schema_kind.append_deref(old_not.as_ref(), "not");
                let new_not = new_schema_kind.append_deref(new_not.as_ref(), "not");
                self.compare_schema_ref_helper(dry_run, comparison, old_not, new_not)
            }
            (&openapiv3::SchemaKind::Any(old_any), &openapiv3::SchemaKind::Any(new_any)) => {
                if old_any == new_any {
                    Ok(true)
                } else {
                    self.schema_push_change(
                        dry_run,
                        "schema kind 'any' changed",
                        &old_schema_kind,
                        &new_schema_kind,
                        comparison,
                        ChangeClass::Unhandled,
                        ChangeDetails::UnknownDifference,
                    )
                }
            }
            _ => {
                let old_tag = SchemaKindTag::new(&old_schema_kind);
                let new_tag = SchemaKindTag::new(&new_schema_kind);
                self.schema_push_change(
                    dry_run,
                    format!("schema kind changed from {} to {}", old_tag, new_tag),
                    &old_schema_kind,
                    &new_schema_kind,
                    comparison,
                    ChangeClass::Incompatible,
                    ChangeDetails::Datatype,
                )
            }
        }
    }

    pub(crate) fn compare_schema_type(
        &mut self,
        comparison: SchemaComparison,
        dry_run: bool,
        old_schema_type: Contextual<'_, &openapiv3::Type>,
        new_schema_type: Contextual<'_, &openapiv3::Type>,
    ) -> anyhow::Result<bool> {
        match (old_schema_type.as_ref(), new_schema_type.as_ref()) {
            (openapiv3::Type::String(old_string), openapiv3::Type::String(new_string)) => {
                if old_string != new_string {
                    self.schema_push_change(
                        dry_run,
                        "string schema changed",
                        &old_schema_type,
                        &new_schema_type,
                        comparison,
                        ChangeClass::Unhandled,
                        ChangeDetails::UnknownDifference,
                    )
                } else {
                    Ok(true)
                }
            }
            (openapiv3::Type::Number(old_number), openapiv3::Type::Number(new_number)) => {
                if old_number != new_number {
                    self.schema_push_change(
                        dry_run,
                        "number schema changed",
                        &old_schema_type,
                        &new_schema_type,
                        comparison,
                        ChangeClass::Unhandled,
                        ChangeDetails::UnknownDifference,
                    )
                } else {
                    Ok(true)
                }
            }
            (openapiv3::Type::Integer(old_integer), openapiv3::Type::Integer(new_integer)) => {
                if old_integer != new_integer {
                    self.schema_push_change(
                        dry_run,
                        "integer schema changed",
                        &old_schema_type,
                        &new_schema_type,
                        comparison,
                        ChangeClass::Unhandled,
                        ChangeDetails::UnknownDifference,
                    )
                } else {
                    Ok(true)
                }
            }
            (openapiv3::Type::Boolean(old_boolean), openapiv3::Type::Boolean(new_boolean)) => {
                if old_boolean != new_boolean {
                    self.schema_push_change(
                        dry_run,
                        "integer schema changed",
                        &old_schema_type,
                        &new_schema_type,
                        comparison,
                        ChangeClass::Unhandled,
                        ChangeDetails::UnknownDifference,
                    )
                } else {
                    Ok(true)
                }
            }
            (openapiv3::Type::Array(old_array), openapiv3::Type::Array(new_array)) => self
                .compare_schema_type_array(
                    comparison,
                    dry_run,
                    old_schema_type.subcomponent(old_array),
                    new_schema_type.subcomponent(new_array),
                ),
            (openapiv3::Type::Object(old_object), openapiv3::Type::Object(new_object)) => self
                .compare_schema_type_object(
                    comparison,
                    dry_run,
                    old_schema_type.subcomponent(old_object),
                    new_schema_type.subcomponent(new_object),
                ),
            _ => self.schema_push_change(
                dry_run,
                "schema types changed",
                &old_schema_type,
                &new_schema_type,
                comparison,
                ChangeClass::Incompatible,
                ChangeDetails::UnknownDifference,
            ),
        }
    }

    fn compare_schema_type_array(
        &mut self,
        comparison: SchemaComparison,
        dry_run: bool,
        old_array: Contextual<'_, &openapiv3::ArrayType>,
        new_array: Contextual<'_, &openapiv3::ArrayType>,
    ) -> anyhow::Result<bool> {
        let ArrayType {
            items: old_items,
            min_items: old_min_items,
            max_items: old_max_items,
            unique_items: old_unique_items,
        } = old_array.as_ref();
        let ArrayType {
            items: new_items,
            min_items: new_min_items,
            max_items: new_max_items,
            unique_items: new_unique_items,
        } = new_array.as_ref();

        let mut ret = true;

        if old_min_items != new_min_items {
            ret = false;
            let _ = self.schema_push_change(
                dry_run,
                "array minItems changed",
                &old_array,
                &new_array,
                comparison,
                ChangeClass::Unhandled,
                ChangeDetails::UnknownDifference,
            );
        }

        if old_max_items != new_max_items {
            ret = false;
            let _ = self.schema_push_change(
                dry_run,
                "array maxItems changed",
                &old_array,
                &new_array,
                comparison,
                ChangeClass::Unhandled,
                ChangeDetails::UnknownDifference,
            );
        }

        if old_unique_items != new_unique_items {
            ret = false;
            let _ = self.schema_push_change(
                dry_run,
                "array uniqueItems changed",
                &old_array,
                &new_array,
                comparison,
                ChangeClass::Unhandled,
                ChangeDetails::UnknownDifference,
            );
        }

        match (old_items, new_items) {
            (Some(old_items), Some(new_items)) => {
                let old_item_schema = old_items.clone().unbox();
                let old_items = old_array.append_deref(&old_item_schema, "items");
                let new_item_schema = new_items.clone().unbox();
                let new_items = new_array.append_deref(&new_item_schema, "items");

                ret &= self.compare_schema_ref_helper(dry_run, comparison, old_items, new_items)?;
            }
            (None, None) => {}
            _ => {
                ret = false;
                let _ = self.schema_push_change(
                    dry_run,
                    "array items changed",
                    &old_array,
                    &new_array,
                    comparison,
                    ChangeClass::Unhandled,
                    ChangeDetails::UnknownDifference,
                );
            }
        }

        Ok(ret)
    }

    fn compare_schema_type_object(
        &mut self,
        comparison: SchemaComparison,
        dry_run: bool,
        old_object: Contextual<'_, &openapiv3::ObjectType>,
        new_object: Contextual<'_, &openapiv3::ObjectType>,
    ) -> anyhow::Result<bool> {
        let ObjectType {
            properties: old_properties,
            required: old_required,
            additional_properties: old_additional_properties,
            min_properties: old_min_properties,
            max_properties: old_max_properties,
        } = old_object.as_ref();
        let ObjectType {
            properties: new_properties,
            required: new_required,
            additional_properties: new_additional_properties,
            min_properties: new_min_properties,
            max_properties: new_max_properties,
        } = new_object.as_ref();

        let mut ret = true;

        if old_required != new_required {
            ret = false;
            let _ = self.schema_push_change(
                dry_run,
                "object required properties changed",
                &old_object,
                &new_object,
                comparison,
                ChangeClass::Unhandled,
                ChangeDetails::UnknownDifference,
            );
        }

        if old_min_properties != new_min_properties {
            ret = false;
            let _ = self.schema_push_change(
                dry_run,
                "object minProperties changed",
                &old_object,
                &new_object,
                comparison,
                ChangeClass::Unhandled,
                ChangeDetails::UnknownDifference,
            );
        }

        if old_max_properties != new_max_properties {
            ret = false;
            let _ = self.schema_push_change(
                dry_run,
                "object maxProperties changed",
                &old_object,
                &new_object,
                comparison,
                ChangeClass::Unhandled,
                ChangeDetails::UnknownDifference,
            );
        }

        match (old_additional_properties, new_additional_properties) {
            (
                Some(AdditionalProperties::Schema(old_ap_schema)),
                Some(AdditionalProperties::Schema(new_ap_schema)),
            ) => {
                let old_ap_schema =
                    old_object.append_deref(old_ap_schema.as_ref(), "additionalProperties");
                let new_ap_schema =
                    new_object.append_deref(new_ap_schema.as_ref(), "additionalProperties");

                ret &= self.compare_schema_ref_helper(
                    dry_run,
                    comparison,
                    old_ap_schema,
                    new_ap_schema,
                )?;
            }

            (Some(AdditionalProperties::Any(false)), Some(AdditionalProperties::Any(false))) => {}

            // Equivalent and not worth reporting any change (i.e. absent is
            // effectively equal to `true`)
            (
                None | Some(AdditionalProperties::Any(true)),
                None | Some(AdditionalProperties::Any(true)),
            ) => {}

            _ => {
                ret = false;
                let _ = self.schema_push_change(
                    dry_run,
                    "object additionalProperties changed",
                    &old_object,
                    &new_object,
                    comparison,
                    ChangeClass::Unhandled,
                    ChangeDetails::UnknownDifference,
                );
            }
        }

        let SetCompare {
            a_unique,
            common,
            b_unique,
        } = SetCompare::new(old_properties, new_properties);

        if !a_unique.is_empty() || !b_unique.is_empty() {
            ret = false;
            let _ = self.schema_push_change(
                dry_run,
                "object properties changed",
                &old_object,
                &new_object,
                comparison,
                ChangeClass::Unhandled,
                ChangeDetails::UnknownDifference,
            );
        }

        let old_prop_context = old_object.context().append("properties");
        let new_prop_context = new_object.context().append("properties");
        for (prop_name, (old_prop, new_prop)) in common {
            let old_prop_schema = old_prop.clone().unbox();
            let old_prop = Contextual::new(old_prop_context.append(prop_name), &old_prop_schema);
            let new_prop_schema = new_prop.clone().unbox();
            let new_prop = Contextual::new(new_prop_context.append(prop_name), &new_prop_schema);

            ret &= self.compare_schema_ref_helper(dry_run, comparison, old_prop, new_prop)?;
        }

        Ok(ret)
    }

    fn compare_schema_type_one_of(
        &mut self,
        comparison: SchemaComparison,
        dry_run: bool,
        old_one_of: Contextual<'_, &Vec<ReferenceOr<Schema>>>,
        new_one_of: Contextual<'_, &Vec<ReferenceOr<Schema>>>,
    ) -> anyhow::Result<bool> {
        let old_schemas = old_one_of.as_ref();
        let new_schemas = new_one_of.as_ref();
        if old_schemas.len() != new_schemas.len() {
            return self.schema_push_change(
                dry_run,
                "oneOf schema count changed",
                &old_one_of,
                &new_one_of,
                comparison,
                ChangeClass::Unhandled,
                ChangeDetails::UnknownDifference,
            );
        }

        // TODO we could be resilient to reordering... but aren't for now.

        let mut ret = true;

        for (idx, (old_schema, new_schema)) in
            old_schemas.iter().zip(new_schemas.iter()).enumerate()
        {
            let old_schema = old_one_of.append_deref(old_schema, &idx.to_string());
            let new_schema = new_one_of.append_deref(new_schema, &idx.to_string());
            ret &= self.compare_schema_ref_helper(dry_run, comparison, old_schema, new_schema)?;
        }

        Ok(ret)
    }

    fn compare_schema_type_all_of(
        &mut self,
        comparison: SchemaComparison,
        dry_run: bool,
        old_all_of: Contextual<'_, &Vec<ReferenceOr<Schema>>>,
        new_all_of: Contextual<'_, &Vec<ReferenceOr<Schema>>>,
    ) -> anyhow::Result<bool> {
        let old_schemas = old_all_of.as_ref();
        let new_schemas = new_all_of.as_ref();

        if old_schemas.len() != new_schemas.len() {
            return self.schema_push_change(
                dry_run,
                "allOf schema count changed",
                &old_all_of,
                &new_all_of,
                comparison,
                ChangeClass::Unhandled,
                ChangeDetails::UnknownDifference,
            );
        }

        if old_schemas.len() != 1 {
            return self.schema_push_change(
                dry_run,
                "allOf with multiple schemas is unhandled",
                &old_all_of,
                &new_all_of,
                comparison,
                ChangeClass::Unhandled,
                ChangeDetails::UnknownDifference,
            );
        }

        let old_single_schema = old_all_of.append_deref(old_all_of.first().unwrap(), "0");
        let new_single_schema = new_all_of.append_deref(new_all_of.first().unwrap(), "0");

        self.compare_schema_ref_helper(dry_run, comparison, old_single_schema, new_single_schema)
    }

    #[allow(clippy::too_many_arguments)]
    fn schema_push_change(
        &mut self,
        dry_run: bool,
        message: impl ToString,
        old: &dyn ToContext<'_>,
        new: &dyn ToContext<'_>,
        comparison: impl Into<ChangeComparison>,
        class: ChangeClass,
        details: ChangeDetails,
    ) -> anyhow::Result<bool> {
        if !dry_run {
            self.push_change(message, old, new, comparison.into(), class, details);
        }
        Ok(false)
    }
}

#[derive(Clone, Debug)]
enum SchemaKindTag {
    Type,
    OneOf,
    AllOf,
    AnyOf,
    Not,
    Any,
}

impl fmt::Display for SchemaKindTag {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Type => write!(f, "regular type"),
            Self::OneOf => write!(f, "oneOf"),
            Self::AllOf => write!(f, "allOf"),
            Self::AnyOf => write!(f, "anyOf"),
            Self::Not => write!(f, "not"),
            Self::Any => write!(f, "any"),
        }
    }
}

impl SchemaKindTag {
    fn new(kind: &openapiv3::SchemaKind) -> Self {
        match kind {
            openapiv3::SchemaKind::Type(_) => Self::Type,
            openapiv3::SchemaKind::OneOf { .. } => Self::OneOf,
            openapiv3::SchemaKind::AllOf { .. } => Self::AllOf,
            openapiv3::SchemaKind::AnyOf { .. } => Self::AnyOf,
            openapiv3::SchemaKind::Not { .. } => Self::Not,
            openapiv3::SchemaKind::Any { .. } => Self::Any,
        }
    }
}

/// Classification of a schema reference for flattening purposes.
enum SchemaRefKind<'a> {
    /// A bare $ref.
    BareRef,
    /// An inline type (Type, Any, Not).
    ///
    /// It is okay to compare something like Not with single-element wrappers.
    /// When recursing, we'll ensure that the child is also Not.
    InlineType,
    /// A single-element allOf/anyOf/oneOf wrapper that can be flattened to its
    /// inner type.
    SingleElement {
        inner: &'a ReferenceOr<Schema>,
        metadata: &'a SchemaData,
    },
    /// Multi (or, less commonly, zero) element allOf/anyOf/oneOf: cannot be
    /// flattened.
    MultiElement,
}

/// Classify a schema reference for flattening purposes.
fn classify_schema_ref(schema_ref: &ReferenceOr<Schema>) -> SchemaRefKind<'_> {
    match schema_ref {
        ReferenceOr::Reference { .. } => SchemaRefKind::BareRef,
        ReferenceOr::Item(schema) => match &schema.schema_kind {
            openapiv3::SchemaKind::Type(_)
            | openapiv3::SchemaKind::Not { .. }
            | openapiv3::SchemaKind::Any(_) => SchemaRefKind::InlineType,
            openapiv3::SchemaKind::AllOf { all_of } if all_of.len() == 1 => {
                SchemaRefKind::SingleElement {
                    inner: all_of.first().unwrap(),
                    metadata: &schema.schema_data,
                }
            }
            openapiv3::SchemaKind::AnyOf { any_of } if any_of.len() == 1 => {
                SchemaRefKind::SingleElement {
                    inner: any_of.first().unwrap(),
                    metadata: &schema.schema_data,
                }
            }
            openapiv3::SchemaKind::OneOf { one_of } if one_of.len() == 1 => {
                SchemaRefKind::SingleElement {
                    inner: one_of.first().unwrap(),
                    metadata: &schema.schema_data,
                }
            }
            // Multi-element wrappers - not semantically equivalent to single schemas.
            openapiv3::SchemaKind::AllOf { .. }
            | openapiv3::SchemaKind::AnyOf { .. }
            | openapiv3::SchemaKind::OneOf { .. } => SchemaRefKind::MultiElement,
        },
    }
}

/// Check if schema_data has any non-default values that would constitute
/// metadata worth preserving.
fn has_meaningful_metadata(data: &SchemaData) -> bool {
    *data != SchemaData::default()
}