Skip to main content

zenkey_model/
compat.rs

1//! The compatibility classifier (spec `core.md` §9.8, #618).
2//!
3//! Revisions inside a major are checked FULL_TRANSITIVE: a candidate
4//! against every earlier revision, in both directions. A change is
5//! [`Class::Compatible`], [`Class::Review`] (a human accepts it) or
6//! [`Class::Breaking`] (CI refuses it); the candidate's class is the worst.
7//!
8//! The classifier works on [`Revision`]s: a canonical contract plus its
9//! schema artifacts. A revision comes from a loaded contract or from a
10//! published bundle, so the `.history` is checked without re-reading
11//! sources.
12//!
13//! - **Contract metadata** follows §9.8's table.
14//! - **Protobuf payloads** use WIRE semantics with renumber detection
15//!   (decided 2026-10-08): a type or cardinality change breaks, a rename is
16//!   review, a field added is compatible, a field deleted without reserving
17//!   its number is compatible with the warning `field_deleted_unreserved`.
18//!   A proto2 `required` label added, removed or toggled breaks: a reader
19//!   refuses a message that lacks it.
20//! - **JSON Schema payloads** use the zk2 subset with tolerant readers;
21//!   anything inside `oneOf`, `anyOf` or `prefixItems` that is not decided
22//!   is review, compared through its `$ref`s. A nullable's two spellings,
23//!   `{"type": [T, "null"]}` and `{"anyOf": [S, {"type": "null"}]}`, are one
24//!   type (spec §7.3, amendment 0.7).
25//! - **Packed payloads** (core §9.8, 0.75) are compared by their layouts,
26//!   item by item: growth behind a marker is compatible, a bound, a
27//!   resolution, a width, `reserved`, `optional` or an enum's order moved is
28//!   breaking, and a rename is review.
29//! - **Retention** ([`same_revision`]): two revisions are the same when
30//!   their canonical forms agree once schema ids are replaced by artifact
31//!   names, and their artifacts agree once protobuf descriptor sets are
32//!   normalized (source info and default `json_name` dropped).
33
34use std::collections::{BTreeMap, BTreeSet};
35
36use base64::Engine as _;
37use prost::Message as _;
38use prost_reflect::{
39    Cardinality, DescriptorPool, EnumDescriptor, FieldDescriptor, Kind, MessageDescriptor,
40};
41use serde_json::{Map, Value};
42
43use crate::bundle::Bundle;
44use crate::canonical::canonical;
45use crate::contract::Contract;
46use crate::schema::{ArtifactData, jcs};
47
48/// How a change is judged.
49#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
50pub enum Class {
51    Compatible,
52    Review,
53    Breaking,
54}
55
56impl Class {
57    #[must_use]
58    pub fn as_str(self) -> &'static str {
59        match self {
60            Self::Compatible => "compatible",
61            Self::Review => "review",
62            Self::Breaking => "breaking",
63        }
64    }
65}
66
67/// One judged change.
68#[derive(Debug, Clone, PartialEq, Eq)]
69pub struct Finding {
70    pub class: Class,
71    /// A stable rule name (`field_renamed`, `resource_removed`, …).
72    pub rule: &'static str,
73    /// Where: `resources."<template>"`, a field path, a role.
74    pub at: String,
75    pub detail: String,
76}
77
78/// The result of comparing a candidate with earlier revisions.
79#[derive(Debug, Clone, Default, PartialEq, Eq)]
80pub struct Verdict {
81    /// Every review and breaking change.
82    pub findings: Vec<Finding>,
83    /// Warnings that do not change the class (`field_deleted_unreserved`).
84    pub warnings: Vec<Finding>,
85}
86
87impl Verdict {
88    /// The worst class found; compatible when there is none.
89    #[must_use]
90    pub fn class(&self) -> Class {
91        self.findings
92            .iter()
93            .map(|f| f.class)
94            .max()
95            .unwrap_or(Class::Compatible)
96    }
97    /// The warning rules, sorted and deduplicated.
98    #[must_use]
99    pub fn warning_rules(&self) -> Vec<&'static str> {
100        let s: BTreeSet<&'static str> = self.warnings.iter().map(|w| w.rule).collect();
101        s.into_iter().collect()
102    }
103    fn push(&mut self, class: Class, rule: &'static str, at: &str, detail: impl Into<String>) {
104        if class == Class::Compatible {
105            return;
106        }
107        self.findings.push(Finding {
108            class,
109            rule,
110            at: at.to_owned(),
111            detail: detail.into(),
112        });
113    }
114    fn warn(&mut self, rule: &'static str, at: &str, detail: impl Into<String>) {
115        self.warnings.push(Finding {
116            class: Class::Compatible,
117            rule,
118            at: at.to_owned(),
119            detail: detail.into(),
120        });
121    }
122    fn extend(&mut self, other: Verdict) {
123        self.findings.extend(other.findings);
124        self.warnings.extend(other.warnings);
125    }
126}
127
128/// A schema artifact of a revision.
129#[derive(Debug, Clone, PartialEq)]
130pub enum Schema {
131    /// An encoded `FileDescriptorSet`.
132    Protobuf(Vec<u8>),
133    /// A JSON Schema document.
134    Json(Value),
135}
136
137/// A revision: its canonical contract and its schema artifacts by id.
138#[derive(Debug, Clone, PartialEq)]
139pub struct Revision {
140    pub canonical: Value,
141    pub schemas: BTreeMap<String, Schema>,
142}
143
144impl Revision {
145    /// Of a loaded contract.
146    #[must_use]
147    pub fn of(c: &Contract) -> Self {
148        let schemas = c
149            .artifacts
150            .iter()
151            .map(|(id, a)| {
152                let s = match &a.data {
153                    ArtifactData::Protobuf(b) => Schema::Protobuf(b.clone()),
154                    ArtifactData::Json(v) => Schema::Json(v.clone()),
155                };
156                (id.clone(), s)
157            })
158            .collect();
159        Self {
160            canonical: canonical(c),
161            schemas,
162        }
163    }
164
165    /// Of a verified bundle.
166    #[must_use]
167    pub fn of_bundle(b: &Bundle) -> Self {
168        let schemas = b
169            .schemas
170            .iter()
171            .filter_map(|(id, e)| {
172                let data = e.get("data")?;
173                let s = match e.get("kind")?.as_str()? {
174                    "protobuf" => Schema::Protobuf(
175                        base64::engine::general_purpose::STANDARD
176                            .decode(data.as_str()?)
177                            .ok()?,
178                    ),
179                    "jsonschema" | "packed" => Schema::Json(data.clone()),
180                    _ => return None,
181                };
182                Some((id.clone(), s))
183            })
184            .collect();
185        Self {
186            canonical: b.contract.clone(),
187            schemas,
188        }
189    }
190
191    fn resources(&self) -> BTreeMap<(String, String), &Value> {
192        self.canonical["resources"]
193            .as_array()
194            .into_iter()
195            .flatten()
196            .filter_map(|r| {
197                Some((
198                    (
199                        r["kind"].as_str()?.to_owned(),
200                        r["template"].as_str()?.to_owned(),
201                    ),
202                    r,
203                ))
204            })
205            .collect()
206    }
207
208    /// JSON Schema documents by file stem (their artifact name). A packed
209    /// document is JSON too, and is left out: a `$ref` never names one.
210    fn json_by_stem(&self) -> BTreeMap<String, &Value> {
211        let names: BTreeMap<&str, &str> = self.canonical["schemas"]
212            .as_array()
213            .into_iter()
214            .flatten()
215            .filter(|s| s["kind"] == "jsonschema")
216            .filter_map(|s| Some((s["id"].as_str()?, s["name"].as_str()?)))
217            .collect();
218        self.schemas
219            .iter()
220            .filter_map(|(id, s)| match s {
221                Schema::Json(v) => Some((names.get(id.as_str())?.to_string(), v)),
222                Schema::Protobuf(_) => None,
223            })
224            .collect()
225    }
226}
227
228/// Classifies `new` against every revision of `history` (FULL_TRANSITIVE).
229#[must_use]
230pub fn check_history(history: &[Revision], new: &Revision) -> Verdict {
231    let mut v = Verdict::default();
232    for old in history {
233        v.extend(compare(old, new));
234    }
235    v
236}
237
238/// Classifies the change from `old` to `new`, both directions.
239#[must_use]
240pub fn compare(old: &Revision, new: &Revision) -> Verdict {
241    let mut v = Verdict::default();
242    if old.canonical["interface"] != new.canonical["interface"] {
243        v.push(
244            Class::Breaking,
245            "interface_changed",
246            "interface",
247            "the interface id differs",
248        );
249        return v;
250    }
251    if old.canonical["uses"] != new.canonical["uses"] {
252        v.push(
253            Class::Review,
254            "uses_changed",
255            "interface.uses",
256            "the profiles used changed",
257        );
258    }
259    let (ro, rn) = (old.resources(), new.resources());
260    for (key, o) in &ro {
261        let at = format!("resources.{:?}", key.1);
262        match rn.get(key) {
263            None => v.push(
264                Class::Breaking,
265                "resource_removed",
266                &at,
267                "removed; a deprecated resource stays until the next major",
268            ),
269            Some(n) => compare_resource(o, n, old, new, &at, &mut v),
270        }
271    }
272    for (key, n) in &rn {
273        if ro.contains_key(key) {
274            continue;
275        }
276        let at = format!("resources.{:?}", key.1);
277        if n["optional"] == Value::Bool(true) {
278            // An optional resource added: old providers simply do not
279            // expose it.
280        } else {
281            v.push(
282                Class::Breaking,
283                "required_resource_added",
284                &at,
285                "a required resource added: old providers lack it",
286            );
287        }
288    }
289    compare_requires(
290        &old.canonical["requires"],
291        &new.canonical["requires"],
292        &mut v,
293    );
294    v
295}
296
297fn s(v: &Value) -> &str {
298    v.as_str().unwrap_or("")
299}
300
301#[allow(clippy::too_many_lines)]
302fn compare_resource(o: &Value, n: &Value, ro: &Revision, rn: &Revision, at: &str, v: &mut Verdict) {
303    // Explicit-ness is in the token.
304    match (s(&o["token"]), s(&n["token"])) {
305        (a, b) if a == b => {}
306        ("stream", "@stream") | ("state", "@state") => {
307            v.push(
308                Class::Breaking,
309                "explicit_set",
310                at,
311                "leaves ambient selectors",
312            );
313        }
314        ("@stream", "stream") | ("@state", "state") => {
315            v.push(
316                Class::Review,
317                "explicit_cleared",
318                at,
319                "joins ambient selectors (link budgets)",
320            );
321        }
322        _ => v.push(
323            Class::Breaking,
324            "token_changed",
325            at,
326            "the kind token changed",
327        ),
328    }
329    if o["params"] != n["params"] {
330        v.push(
331            Class::Breaking,
332            "params_changed",
333            at,
334            "a parameter's type changed",
335        );
336    }
337    match (o["optional"].as_bool(), n["optional"].as_bool()) {
338        (Some(true), Some(false)) => {
339            v.push(
340                Class::Breaking,
341                "optional_to_required",
342                at,
343                "old implementers may not expose it",
344            );
345        }
346        (Some(false), Some(true)) => {
347            v.push(
348                Class::Breaking,
349                "required_to_optional",
350                at,
351                "old consumers rely on it",
352            );
353        }
354        _ => {}
355    }
356    for (field, rule) in [
357        ("cardinality", "cardinality_changed"),
358        ("epoch", "epoch_changed"),
359        ("gate", "gate_changed"),
360        ("annotations", "annotations_changed"),
361    ] {
362        if o[field] != n[field] {
363            v.push(Class::Review, rule, at, format!("`{field}` changed"));
364        }
365    }
366    if o["deprecated"] != n["deprecated"] && !n["deprecated"].is_null() && o["deprecated"].is_null()
367    {
368        // Deprecating is compatible; anything else about it is review.
369    } else if o["deprecated"] != n["deprecated"] {
370        v.push(
371            Class::Review,
372            "deprecated_changed",
373            at,
374            "`deprecated` changed",
375        );
376    }
377    if s(&o["kind"]) != s(&n["kind"]) {
378        v.push(
379            Class::Breaking,
380            "kind_changed",
381            at,
382            "the resource kind changed",
383        );
384        return;
385    }
386    if o["encoding"] != n["encoding"] {
387        v.push(
388            Class::Breaking,
389            "encoding_changed",
390            at,
391            "the payload encoding changed",
392        );
393    }
394    if s(&o["kind"]) == "operation" {
395        for (field, what) in [("request", Dir::Request), ("response", Dir::Response)] {
396            compare_type(
397                &o[field],
398                &n[field],
399                ro,
400                rn,
401                &format!("{at}.{field}"),
402                what,
403                v,
404            );
405        }
406        for (field, rule) in [
407            ("error", "error_type_changed"),
408            ("summary", "summary_type_changed"),
409        ] {
410            match (o[field].is_null(), n[field].is_null()) {
411                (true, true) => {}
412                (false, false) => compare_type(
413                    &o[field],
414                    &n[field],
415                    ro,
416                    rn,
417                    &format!("{at}.{field}"),
418                    Dir::Response,
419                    v,
420                ),
421                _ => v.push(
422                    Class::Review,
423                    rule,
424                    at,
425                    format!("`{field}` added or removed"),
426                ),
427            }
428        }
429        if o["idempotent"] == Value::Bool(true) && n["idempotent"] == Value::Bool(false) {
430            v.push(
431                Class::Breaking,
432                "idempotent_cleared",
433                at,
434                "callers may retry it",
435            );
436        } else if o["idempotent"] != n["idempotent"] {
437            v.push(
438                Class::Review,
439                "idempotent_set",
440                at,
441                "new callers may retry old servers",
442            );
443        }
444        if s(&o["fanout"]) == "allowed" && s(&n["fanout"]) == "forbidden" {
445            v.push(
446                Class::Breaking,
447                "fanout_forbidden",
448                at,
449                "fan-out calls are refused",
450            );
451        }
452        if s(&o["replies"]) == "one" && s(&n["replies"]) == "many" {
453            v.push(
454                Class::Breaking,
455                "replies_many",
456                at,
457                "callers' consolidation drops replies",
458            );
459        }
460        for (field, rule) in [
461            ("serving", "serving_changed"),
462            ("timeout_ms", "timeout_changed"),
463            ("priority", "priority_changed"),
464        ] {
465            if o[field] != n[field] {
466                v.push(Class::Review, rule, at, format!("`{field}` changed"));
467            }
468        }
469        return;
470    }
471    compare_type(
472        &o["type"],
473        &n["type"],
474        ro,
475        rn,
476        &format!("{at}.type"),
477        Dir::Data,
478        v,
479    );
480    match (o["attachment"].is_null(), n["attachment"].is_null()) {
481        (true, true) => {}
482        (false, false) => compare_type(
483            &o["attachment"],
484            &n["attachment"],
485            ro,
486            rn,
487            &format!("{at}.attachment"),
488            Dir::Data,
489            v,
490        ),
491        _ => v.push(
492            Class::Review,
493            "attachment_changed",
494            at,
495            "an attachment added or removed",
496        ),
497    }
498    if o["attachment_encoding"] != n["attachment_encoding"]
499        && !o["attachment"].is_null()
500        && !n["attachment"].is_null()
501    {
502        v.push(
503            Class::Breaking,
504            "encoding_changed",
505            at,
506            "the attachment encoding changed",
507        );
508    }
509    if s(&o["reliability"]) == "reliable" && s(&n["reliability"]) == "best_effort" {
510        v.push(
511            Class::Review,
512            "reliability_lowered",
513            at,
514            "reliable → best_effort",
515        );
516    }
517    if o["congestion"] != n["congestion"] {
518        v.push(
519            Class::Review,
520            "congestion_changed",
521            at,
522            "drop ↔ block (it can stall the producer, or drop)",
523        );
524    }
525    for (field, rule) in [
526        ("priority", "priority_changed"),
527        ("express", "express_toggled"),
528        ("history", "history_changed"),
529        ("rate", "rate_changed"),
530        ("retention_s", "retention_changed"),
531    ] {
532        if o[field] != n[field] {
533            v.push(Class::Review, rule, at, format!("`{field}` changed"));
534        }
535    }
536    let fields = if o.get("frame").is_some() && n.get("frame").is_some() {
537        (field_names(ro, &o["type"]), field_names(rn, &n["type"]))
538    } else {
539        (None, None)
540    };
541    compare_frame(o.get("frame"), n.get("frame"), &fields, at, v);
542}
543
544/// A packed type's field names, in its record's order: where a frame form
545/// places each deadband (core §7.7). `None` for a type that is not packed,
546/// or whose artifact does not lay it out.
547fn field_names(r: &Revision, t: &Value) -> Option<Vec<String>> {
548    if s(&t["kind"]) != "packed" {
549        return None;
550    }
551    let doc = match r.schemas.get(s(&t["schema"]))? {
552        Schema::Json(doc) => doc,
553        Schema::Protobuf(_) => return None,
554    };
555    let layout = crate::packed::PackedDoc::read(doc)
556        .types
557        .remove(s(&t["name"]))
558        .flatten()?;
559    Some(
560        layout
561            .items
562            .iter()
563            .filter_map(|i| match i {
564                crate::packed::Item::Field(f) => Some(f.name.clone()),
565                crate::packed::Item::Marker => None,
566            })
567            .collect(),
568    )
569}
570
571/// A frame resource's table (core §9.8, "Frames"): `frame` toggled, its
572/// shape or a deadband changed, all breaking, since each moves the
573/// frame's tag; `keyframe_every`, review. A deadband is compared by its
574/// field's place in the record, `fields` each revision's field names, as
575/// the frame form lists it, so a field renamed keeps its deadband; by
576/// name where a record does not lay out, or the two differ in length,
577/// which the layout's own change reports. The record type is the packed
578/// rules', compared as the resource's type.
579fn compare_frame(
580    o: Option<&Value>,
581    n: Option<&Value>,
582    fields: &(Option<Vec<String>>, Option<Vec<String>>),
583    at: &str,
584    v: &mut Verdict,
585) {
586    let (o, n) = match (o, n) {
587        (None, None) => return,
588        (Some(o), Some(n)) => (o, n),
589        _ => {
590            v.push(
591                Class::Breaking,
592                "frame_toggled",
593                at,
594                "`frame` added or removed: a reader of the other revision reads none of its samples",
595            );
596            return;
597        }
598    };
599    if ["records", "step_ms", "jitter_ms"]
600        .iter()
601        .any(|k| o[*k] != n[*k])
602    {
603        v.push(
604            Class::Breaking,
605            "frame_changed",
606            at,
607            "`records`, `step_ms` or `jitter_ms` changed: the bits and the times move",
608        );
609    }
610    let deadbands_differ = match fields {
611        (Some(old), Some(new)) if old.len() == new.len() => old
612            .iter()
613            .zip(new)
614            .any(|(a, b)| o["deadband"].get(a.as_str()) != n["deadband"].get(b.as_str())),
615        _ => o["deadband"] != n["deadband"],
616    };
617    if deadbands_differ {
618        v.push(
619            Class::Breaking,
620            "deadband_changed",
621            at,
622            "a deadband added, removed or changed: what an omitted field holds moves",
623        );
624    }
625    if o["keyframe_every"] != n["keyframe_every"] {
626        v.push(
627            Class::Review,
628            "keyframe_changed",
629            at,
630            "`keyframe_every` changed: how long a reader waits to heal",
631        );
632    }
633}
634
635fn compare_requires(o: &Value, n: &Value, v: &mut Verdict) {
636    let empty = Map::new();
637    let (o, n) = (
638        o.as_object().unwrap_or(&empty),
639        n.as_object().unwrap_or(&empty),
640    );
641    for (role, ro) in o {
642        let at = format!("requires.{role}");
643        let Some(rn) = n.get(role) else {
644            // A role removed: deployments stop binding it.
645            continue;
646        };
647        if ro["interface"] != rn["interface"] || ro["cardinality"] != rn["cardinality"] {
648            v.push(
649                Class::Breaking,
650                "role_changed",
651                &at,
652                "the role's interface or cardinality changed",
653            );
654        }
655        if ro["optional"] == Value::Bool(true) && rn["optional"] == Value::Bool(false) {
656            v.push(
657                Class::Breaking,
658                "role_required",
659                &at,
660                "deployments must now bind it",
661            );
662        }
663        if ro["resources"] != rn["resources"] || ro["annotations"] != rn["annotations"] {
664            v.push(
665                Class::Review,
666                "role_resources_changed",
667                &at,
668                "what the role consumes changed",
669            );
670        }
671    }
672    for (role, rn) in n {
673        if !o.contains_key(role) && rn["optional"] != Value::Bool(true) {
674            v.push(
675                Class::Breaking,
676                "required_role_added",
677                &format!("requires.{role}"),
678                "deployments must bind it",
679            );
680        }
681    }
682}
683
684/// Which side writes a payload. The classification is the same both ways
685/// (FULL), so this only names the place in findings.
686#[derive(Debug, Clone, Copy)]
687enum Dir {
688    Data,
689    Request,
690    Response,
691}
692
693fn compare_type(
694    o: &Value,
695    n: &Value,
696    ro: &Revision,
697    rn: &Revision,
698    at: &str,
699    _dir: Dir,
700    v: &mut Verdict,
701) {
702    match (s(&o["kind"]), s(&n["kind"])) {
703        ("raw", "raw") => {
704            if o["media_type"] != n["media_type"] {
705                v.push(
706                    Class::Breaking,
707                    "media_type_changed",
708                    at,
709                    "the raw media type changed",
710                );
711            } else if o["media_param"] != n["media_param"] {
712                v.push(
713                    Class::Review,
714                    "media_param_changed",
715                    at,
716                    "`media_param` changed",
717                );
718            }
719        }
720        ("protobuf", "protobuf") => {
721            let (Some(po), Some(pn)) = (pool(ro, &o["schema"]), pool(rn, &n["schema"])) else {
722                v.push(
723                    Class::Review,
724                    "schema_unreadable",
725                    at,
726                    "a descriptor set does not decode",
727                );
728                return;
729            };
730            match (
731                po.get_message_by_name(s(&o["name"])),
732                pn.get_message_by_name(s(&n["name"])),
733            ) {
734                (Some(mo), Some(mn)) => {
735                    let mut seen = BTreeSet::new();
736                    compare_messages(&mo, &mn, at, &mut seen, v);
737                }
738                _ => v.push(
739                    Class::Review,
740                    "schema_unreadable",
741                    at,
742                    "a message is missing from its descriptor set",
743                ),
744            }
745        }
746        ("jsonschema", "jsonschema") => {
747            let (Some(Schema::Json(doc_old)), Some(Schema::Json(doc_new))) = (
748                ro.schemas.get(s(&o["schema"])),
749                rn.schemas.get(s(&n["schema"])),
750            ) else {
751                v.push(
752                    Class::Review,
753                    "schema_unreadable",
754                    at,
755                    "a JSON Schema artifact is missing",
756                );
757                return;
758            };
759            let cx = JsonCx {
760                old_docs: ro.json_by_stem(),
761                new_docs: rn.json_by_stem(),
762            };
763            let so = doc_old["$defs"][s(&o["name"])].clone();
764            let sn = doc_new["$defs"][s(&n["name"])].clone();
765            let mut seen = BTreeSet::new();
766            cx.compare(&so, doc_old, &sn, doc_new, at, &mut seen, v);
767        }
768        ("packed", "packed") => {
769            let layout = |r: &Revision, t: &Value| match r.schemas.get(s(&t["schema"])) {
770                Some(Schema::Json(doc)) => crate::packed::PackedDoc::read(doc)
771                    .types
772                    .remove(s(&t["name"]))
773                    .flatten(),
774                _ => None,
775            };
776            match (layout(ro, o), layout(rn, n)) {
777                (Some(lo), Some(ln)) => compare_packed(&lo, &ln, at, v),
778                _ => v.push(
779                    Class::Review,
780                    "schema_unreadable",
781                    at,
782                    "a packed artifact is missing, or does not lay out its type",
783                ),
784            }
785        }
786        _ => v.push(
787            Class::Breaking,
788            "type_kind_changed",
789            at,
790            "the schema kind changed",
791        ),
792    }
793}
794
795/// Packed payloads (core §9.8, 0.75): item by item from the first; a
796/// different length is growth behind a marker when the shorter list ends
797/// with one.
798fn compare_packed(o: &crate::packed::Layout, n: &crate::packed::Layout, at: &str, v: &mut Verdict) {
799    use crate::packed::Item;
800    let (a, b) = (&o.items, &n.items);
801    for (i, (x, y)) in a.iter().zip(b).enumerate() {
802        let at = format!("{at}.fields[{i}]");
803        match (x, y) {
804            (Item::Marker, Item::Marker) => {}
805            (Item::Field(x), Item::Field(y)) => compare_packed_fields(x, y, &at, v),
806            _ => v.push(
807                Class::Breaking,
808                "fields_changed",
809                &at,
810                "a marker where the other revision has a field",
811            ),
812        }
813    }
814    if a.len() != b.len() {
815        let shorter = if a.len() < b.len() { a } else { b };
816        if !matches!(shorter.last(), Some(Item::Marker)) {
817            v.push(
818                Class::Breaking,
819                "fields_changed",
820                at,
821                "fields added or removed where no marker ends the shorter revision",
822            );
823        }
824    }
825}
826
827fn compare_packed_fields(
828    x: &crate::packed::Field,
829    y: &crate::packed::Field,
830    at: &str,
831    v: &mut Verdict,
832) {
833    use crate::packed::FieldKind as K;
834    if x.kind.as_str() != y.kind.as_str() {
835        v.push(
836            Class::Breaking,
837            "type_changed",
838            at,
839            format!("{} became {}", x.kind.as_str(), y.kind.as_str()),
840        );
841        return;
842    }
843    if x.name != y.name {
844        v.push(
845            Class::Review,
846            "field_renamed",
847            at,
848            format!("{:?} renamed {:?}", x.name, y.name),
849        );
850    }
851    if x.optional != y.optional {
852        v.push(
853            Class::Breaking,
854            "presence_changed",
855            at,
856            "`optional` toggled: the presence bit appears or goes",
857        );
858    }
859    let bound = |v: &mut Verdict| {
860        v.push(Class::Breaking, "bound_changed", at, "a bound moved");
861    };
862    let reserved = |v: &mut Verdict| {
863        v.push(
864            Class::Breaking,
865            "reserved_changed",
866            at,
867            "`reserved` changed: the codes move",
868        );
869    };
870    match (&x.kind, &y.kind) {
871        (
872            K::Int {
873                minimum: a0,
874                maximum: a1,
875                reserved: ra,
876            },
877            K::Int {
878                minimum: b0,
879                maximum: b1,
880                reserved: rb,
881            },
882        ) => {
883            if (a0, a1) != (b0, b1) {
884                bound(v);
885            }
886            if ra != rb {
887                reserved(v);
888            }
889        }
890        (
891            K::Fixed {
892                minimum: a0,
893                maximum: a1,
894                resolution: ar,
895                reserved: ra,
896                ..
897            },
898            K::Fixed {
899                minimum: b0,
900                maximum: b1,
901                resolution: br,
902                reserved: rb,
903                ..
904            },
905        ) => {
906            if (a0, a1) != (b0, b1) {
907                bound(v);
908            }
909            if ar != br {
910                v.push(
911                    Class::Breaking,
912                    "resolution_changed",
913                    at,
914                    format!("`resolution` {ar} became {br}"),
915                );
916            }
917            if ra != rb {
918                reserved(v);
919            }
920        }
921        (
922            K::Enum {
923                values: va,
924                escape: ea,
925            },
926            K::Enum {
927                values: vb,
928                escape: eb,
929            },
930        ) => {
931            if x.width != y.width {
932                v.push(
933                    Class::Breaking,
934                    "width_changed",
935                    at,
936                    format!("the enum's width {} became {}", x.width, y.width),
937                );
938            }
939            // Every change is reported, the escape's beside the values':
940            // a reader of either revision meets them all.
941            if ea != eb {
942                v.push(Class::Breaking, "enum_changed", at, "the escape toggled");
943            }
944            for (p, q) in va.iter().zip(vb) {
945                if p == q {
946                    continue;
947                }
948                if vb.contains(p) || va.contains(q) {
949                    v.push(
950                        Class::Breaking,
951                        "enum_changed",
952                        at,
953                        format!("{p:?} or {q:?} moved to another index"),
954                    );
955                } else {
956                    v.push(
957                        Class::Review,
958                        "enum_value_renamed",
959                        at,
960                        format!("{p:?} renamed {q:?}"),
961                    );
962                }
963            }
964            // An escape reads an added or removed value only when both
965            // revisions have one.
966            match (vb.len().cmp(&va.len()), *ea && *eb) {
967                (std::cmp::Ordering::Equal, _) | (std::cmp::Ordering::Greater, true) => {}
968                (std::cmp::Ordering::Less, true) => v.push(
969                    Class::Review,
970                    "enum_value_removed",
971                    at,
972                    "a value removed: an old writer still writes it, and a new reader reads the escape",
973                ),
974                (_, false) => v.push(
975                    Class::Breaking,
976                    "enum_changed",
977                    at,
978                    "a value added or removed where no escape reads it",
979                ),
980            }
981        }
982        (K::Counter, K::Counter) | (K::Time { .. }, K::Time { .. }) if x.width != y.width => {
983            v.push(
984                Class::Breaking,
985                "width_changed",
986                at,
987                format!("the width {} became {}", x.width, y.width),
988            );
989        }
990        _ => {}
991    }
992}
993
994fn pool(r: &Revision, id: &Value) -> Option<DescriptorPool> {
995    match r.schemas.get(id.as_str()?)? {
996        Schema::Protobuf(b) => DescriptorPool::decode(b.as_slice()).ok(),
997        Schema::Json(_) => None,
998    }
999}
1000
1001fn reserved(m: &MessageDescriptor, number: u32) -> bool {
1002    m.reserved_ranges().any(|r| r.contains(&number))
1003}
1004
1005fn compare_messages(
1006    o: &MessageDescriptor,
1007    n: &MessageDescriptor,
1008    at: &str,
1009    seen: &mut BTreeSet<(String, String)>,
1010    v: &mut Verdict,
1011) {
1012    if !seen.insert((o.full_name().to_owned(), n.full_name().to_owned())) {
1013        return;
1014    }
1015    for fo in o.fields() {
1016        let fat = format!("{at}.{}", fo.name());
1017        match n.get_field(fo.number()) {
1018            Some(fnew) => {
1019                if fo.name() != fnew.name() {
1020                    v.push(
1021                        Class::Review,
1022                        "field_renamed",
1023                        &fat,
1024                        format!("now {:?}", fnew.name()),
1025                    );
1026                } else if fo.json_name() != fnew.json_name() {
1027                    v.push(
1028                        Class::Review,
1029                        "json_name_changed",
1030                        &fat,
1031                        format!("now {:?}", fnew.json_name()),
1032                    );
1033                }
1034                if fo.is_list() != fnew.is_list() || fo.is_map() != fnew.is_map() {
1035                    v.push(
1036                        Class::Breaking,
1037                        "cardinality_changed",
1038                        &fat,
1039                        "repeated, map or singular changed",
1040                    );
1041                    continue;
1042                }
1043                if is_required(&fo) != is_required(&fnew) {
1044                    v.push(
1045                        Class::Breaking,
1046                        "required_label_changed",
1047                        &fat,
1048                        "proto2 `required` toggled",
1049                    );
1050                }
1051                let oneof = |f: &prost_reflect::FieldDescriptor| {
1052                    f.containing_oneof()
1053                        .filter(|o| !o.is_synthetic())
1054                        .map(|o| o.name().to_owned())
1055                };
1056                if oneof(&fo) != oneof(&fnew) {
1057                    v.push(
1058                        Class::Breaking,
1059                        "oneof_changed",
1060                        &fat,
1061                        "moved into or out of a oneof",
1062                    );
1063                } else if fo.supports_presence() != fnew.supports_presence() && !fo.is_list() {
1064                    v.push(
1065                        Class::Review,
1066                        "presence_changed",
1067                        &fat,
1068                        "explicit presence toggled",
1069                    );
1070                }
1071                compare_kinds(&fo.kind(), &fnew.kind(), &fat, seen, v);
1072            }
1073            None => {
1074                if is_required(&fo) && n.get_field_by_name(fo.name()).is_none() {
1075                    v.push(
1076                        Class::Breaking,
1077                        "required_field_removed",
1078                        &fat,
1079                        "a proto2 `required` field deleted: old readers refuse what new writers send",
1080                    );
1081                }
1082                if let Some(moved) = n.get_field_by_name(fo.name()) {
1083                    v.push(
1084                        Class::Breaking,
1085                        "renumbered",
1086                        &fat,
1087                        format!(
1088                            "{} → {}: the data is dropped both ways",
1089                            fo.number(),
1090                            moved.number()
1091                        ),
1092                    );
1093                } else if !reserved(n, fo.number()) {
1094                    v.warn(
1095                        "field_deleted_unreserved",
1096                        &fat,
1097                        format!("field {} deleted without reserving its number", fo.number()),
1098                    );
1099                }
1100            }
1101        }
1102    }
1103    for fnew in n.fields() {
1104        if o.get_field(fnew.number()).is_some() || o.get_field_by_name(fnew.name()).is_some() {
1105            continue;
1106        }
1107        if is_required(&fnew) {
1108            v.push(
1109                Class::Breaking,
1110                "required_field_added",
1111                &format!("{at}.{}", fnew.name()),
1112                "a proto2 `required` field added: new readers refuse what old writers send",
1113            );
1114        }
1115        if reserved(o, fnew.number()) {
1116            v.push(
1117                Class::Breaking,
1118                "reserved_reused",
1119                &format!("{at}.{}", fnew.name()),
1120                format!("number {} was reserved", fnew.number()),
1121            );
1122        }
1123    }
1124}
1125
1126fn is_required(f: &FieldDescriptor) -> bool {
1127    f.cardinality() == Cardinality::Required
1128}
1129
1130fn compare_kinds(
1131    o: &Kind,
1132    n: &Kind,
1133    at: &str,
1134    seen: &mut BTreeSet<(String, String)>,
1135    v: &mut Verdict,
1136) {
1137    match (o, n) {
1138        (Kind::Message(mo), Kind::Message(mn)) => compare_messages(mo, mn, at, seen, v),
1139        (Kind::Enum(eo), Kind::Enum(en)) => compare_enums(eo, en, at, v),
1140        (a, b) if std::mem::discriminant(a) == std::mem::discriminant(b) => {}
1141        _ => v.push(
1142            Class::Breaking,
1143            "type_changed",
1144            at,
1145            format!("{o:?} → {n:?}"),
1146        ),
1147    }
1148}
1149
1150fn compare_enums(o: &EnumDescriptor, n: &EnumDescriptor, at: &str, v: &mut Verdict) {
1151    for vo in o.values() {
1152        match n.get_value(vo.number()) {
1153            None => v.push(
1154                Class::Review,
1155                "enum_value_removed",
1156                at,
1157                format!("{} removed", vo.name()),
1158            ),
1159            Some(vn) if vn.name() != vo.name() => {
1160                v.push(
1161                    Class::Review,
1162                    "enum_value_renamed",
1163                    at,
1164                    format!("{} → {}", vo.name(), vn.name()),
1165                );
1166            }
1167            Some(_) => {}
1168        }
1169    }
1170    let closed = n.parent_file().syntax() == prost_reflect::Syntax::Proto2;
1171    if closed && n.values().any(|vn| o.get_value(vn.number()).is_none()) {
1172        v.push(
1173            Class::Review,
1174            "closed_enum_value_added",
1175            at,
1176            "a proto2 (closed) enum gained a value: old readers fall back to the default",
1177        );
1178    }
1179}
1180
1181/// JSON Schema comparison context: every listed document of each side, by
1182/// stem, to follow `$ref`s across files.
1183struct JsonCx<'a> {
1184    old_docs: BTreeMap<String, &'a Value>,
1185    new_docs: BTreeMap<String, &'a Value>,
1186}
1187
1188const ANNOTATIONS: &[&str] = &[
1189    "$schema",
1190    "$id",
1191    "$comment",
1192    "title",
1193    "description",
1194    "default",
1195    "examples",
1196    "format",
1197    "deprecated",
1198    "readOnly",
1199    "writeOnly",
1200];
1201const BOUNDS: &[&str] = &[
1202    "minimum",
1203    "maximum",
1204    "exclusiveMinimum",
1205    "exclusiveMaximum",
1206    "minLength",
1207    "maxLength",
1208    "minItems",
1209    "maxItems",
1210];
1211
1212/// A schema without its annotations, at every schema position
1213/// ([`crate::schema::visit_schemas`]'s): what a change inside an undecided
1214/// keyword is compared on. Property names and data (`enum`, `const`) are
1215/// kept as written, so a property named `title` is not an annotation. An
1216/// array is a list of schemas (the value of `oneOf`, `anyOf`,
1217/// `prefixItems`).
1218fn strip(v: &Value) -> Value {
1219    match v {
1220        Value::Object(m) => Value::Object(
1221            m.iter()
1222                .filter(|(k, _)| !ANNOTATIONS.contains(&k.as_str()))
1223                .map(|(k, x)| {
1224                    let x = match (k.as_str(), x) {
1225                        ("properties" | "$defs", Value::Object(subs)) => {
1226                            Value::Object(subs.iter().map(|(n, s)| (n.clone(), strip(s))).collect())
1227                        }
1228                        (
1229                            "prefixItems" | "oneOf" | "anyOf" | "items" | "additionalProperties",
1230                            sub,
1231                        ) => strip(sub),
1232                        (_, x) => x.clone(),
1233                    };
1234                    (k.clone(), x)
1235                })
1236                .collect(),
1237        ),
1238        Value::Array(a) => Value::Array(a.iter().map(strip).collect()),
1239        x => x.clone(),
1240    }
1241}
1242
1243fn types(s: &Value) -> BTreeSet<String> {
1244    match &s["type"] {
1245        Value::String(t) => [t.clone()].into(),
1246        Value::Array(a) => a
1247            .iter()
1248            .filter_map(|t| t.as_str().map(str::to_owned))
1249            .collect(),
1250        _ => BTreeSet::new(),
1251    }
1252}
1253
1254/// The null schema of a nullable form (spec §7.3): its `type` exactly
1255/// `null`, and nothing else that carries meaning.
1256fn is_null_schema(s: &Value) -> bool {
1257    s.as_object().is_some_and(|m| {
1258        m.keys()
1259            .all(|k| k == "type" || ANNOTATIONS.contains(&k.as_str()))
1260    }) && types(s) == BTreeSet::from(["null".to_owned()])
1261}
1262
1263/// The reading of a nullable form (spec §7.3, 0.7, C-1): `{"anyOf": [S,
1264/// {"type": "null"}]}`, the branches in either order and nothing beside the
1265/// `anyOf` that carries meaning, read as S (its `$ref`s followed) with
1266/// `null` added to its `type` and, where it has one, its `enum`. `None` when
1267/// `s` is not the form, or its S, once followed, is not an object with a
1268/// `type` and without `const`, `oneOf` or `anyOf`: such an `anyOf` is
1269/// compared as written.
1270///
1271/// `follow` resolves S's `$ref`s, as the caller's documents hold them, and
1272/// returns what it read beside the schema (the classifier, the document
1273/// the target lives in); `None` when a `$ref` resolves to nothing. The
1274/// classifier reads a form through it, and so does a generator's check that
1275/// a type agrees with its committed schema (`zenkey_build::check_schema`):
1276/// one reading, wherever two schemas are compared for meaning (§7.3).
1277pub fn nullable_reading<T>(
1278    s: &Value,
1279    follow: impl FnOnce(&Value) -> Option<(Value, T)>,
1280) -> Option<(Value, T)> {
1281    let m = s.as_object()?;
1282    if m.keys()
1283        .any(|k| k != "anyOf" && !ANNOTATIONS.contains(&k.as_str()))
1284    {
1285        return None;
1286    }
1287    let [a, b] = m.get("anyOf")?.as_array()?.as_slice() else {
1288        return None;
1289    };
1290    let branch = match (is_null_schema(a), is_null_schema(b)) {
1291        (true, false) => b,
1292        (false, true) => a,
1293        _ => return None,
1294    };
1295    let (mut read, beside) = follow(branch)?;
1296    let r = read.as_object_mut()?;
1297    let typed = match r.get("type") {
1298        Some(Value::String(_)) => true,
1299        Some(Value::Array(a)) => a.iter().all(Value::is_string),
1300        _ => false,
1301    };
1302    if !typed
1303        || ["const", "oneOf", "anyOf"]
1304            .iter()
1305            .any(|k| r.contains_key(*k))
1306    {
1307        return None;
1308    }
1309    let mut t = types(&Value::Object(r.clone()));
1310    t.insert("null".to_owned());
1311    r.insert(
1312        "type".to_owned(),
1313        Value::Array(t.into_iter().map(Value::from).collect()),
1314    );
1315    if let Some(Value::Array(e)) = r.get_mut("enum")
1316        && !e.contains(&Value::Null)
1317    {
1318        e.push(Value::Null);
1319    }
1320    Some((read, beside))
1321}
1322
1323/// An `enum` as the set of its values: order carries no meaning.
1324fn values(e: Option<&Value>) -> Option<BTreeSet<Vec<u8>>> {
1325    e.map(|e| e.as_array().into_iter().flatten().map(jcs).collect())
1326}
1327
1328fn required(s: &Value) -> BTreeSet<String> {
1329    s["required"]
1330        .as_array()
1331        .into_iter()
1332        .flatten()
1333        .filter_map(|r| r.as_str().map(str::to_owned))
1334        .collect()
1335}
1336
1337impl<'a> JsonCx<'a> {
1338    /// Follows `$ref` to its target, and the document the target lives in.
1339    /// A `$ref`'s file part names an artifact by the stem of its last path
1340    /// segment (spec §9.4): a bundle keeps no paths. Keywords beside a
1341    /// `$ref` (other than `$defs`) are added to its target, the outermost
1342    /// taking the place of the target's own, so a change beside a `$ref` is
1343    /// compared like any other.
1344    ///
1345    /// `None` when a `$ref` resolves to nothing: its file part names no
1346    /// artifact of the revision, or its pointer no member. A conforming
1347    /// builder never writes such a bundle (E032, and E024 for a taken id,
1348    /// spec §9.4), so it is unreadable, as a descriptor set that does not
1349    /// decode is: never resolved in the referencing document instead.
1350    fn deref(&self, s: &Value, doc: &'a Value, old: bool) -> Option<(Value, &'a Value)> {
1351        let mut cur = s.clone();
1352        let mut doc = doc;
1353        let mut beside: Vec<Map<String, Value>> = Vec::new();
1354        for _ in 0..32 {
1355            let Some(r) = cur.get("$ref").and_then(Value::as_str).map(str::to_owned) else {
1356                break;
1357            };
1358            if let Value::Object(m) = &cur {
1359                let sib: Map<String, Value> = m
1360                    .iter()
1361                    .filter(|(k, _)| !matches!(k.as_str(), "$ref" | "$defs"))
1362                    .map(|(k, x)| (k.clone(), x.clone()))
1363                    .collect();
1364                if !sib.is_empty() {
1365                    beside.push(sib);
1366                }
1367            }
1368            let (file, ptr) = r.split_once('#').unwrap_or((r.as_str(), ""));
1369            if !file.is_empty() {
1370                let base = file.rsplit('/').next().unwrap_or(file);
1371                let stem = base.strip_suffix(".json").unwrap_or(base);
1372                let docs = if old { &self.old_docs } else { &self.new_docs };
1373                doc = docs.get(stem)?;
1374            }
1375            cur = doc.pointer(ptr)?.clone();
1376        }
1377        if !beside.is_empty() && cur != Value::Bool(false) {
1378            let mut merged = match cur {
1379                Value::Object(m) => m,
1380                _ => Map::new(),
1381            };
1382            for sib in beside.into_iter().rev() {
1383                merged.extend(sib);
1384            }
1385            cur = Value::Object(merged);
1386        }
1387        Some((cur, doc))
1388    }
1389
1390    /// The reading of a nullable form ([`nullable_reading`]), its S
1391    /// followed through this side's documents.
1392    fn nullable(&self, s: &Value, doc: &'a Value, old: bool) -> Option<(Value, &'a Value)> {
1393        nullable_reading(s, |branch| self.deref(branch, doc, old))
1394    }
1395
1396    /// A schema as an undecided keyword compares it (spec §9.8, 0.7):
1397    /// annotations dropped at schema positions, as [`strip`] does, and every
1398    /// `$ref` replaced by its target, siblings merged as [`JsonCx::deref`]
1399    /// does. A `$ref` back to a target already being written stays as
1400    /// written, so a recursive type ends. `None` when a `$ref` resolves to
1401    /// nothing in its revision.
1402    fn written(
1403        &self,
1404        v: &Value,
1405        doc: &'a Value,
1406        old: bool,
1407        stack: &mut Vec<Vec<u8>>,
1408    ) -> Option<Value> {
1409        match v {
1410            Value::Array(a) => a.iter().map(|x| self.written(x, doc, old, stack)).collect(),
1411            Value::Object(m) if m.contains_key("$ref") => {
1412                let (target, tdoc) = self.deref(v, doc, old)?;
1413                let id = jcs(&target);
1414                if stack.contains(&id) {
1415                    return Some(strip(v));
1416                }
1417                stack.push(id);
1418                let out = self.written(&target, tdoc, old, stack);
1419                stack.pop();
1420                out
1421            }
1422            Value::Object(m) => {
1423                let mut out = Map::new();
1424                for (k, x) in m {
1425                    if ANNOTATIONS.contains(&k.as_str()) {
1426                        continue;
1427                    }
1428                    let x = match (k.as_str(), x) {
1429                        ("properties" | "$defs", Value::Object(subs)) => Value::Object(
1430                            subs.iter()
1431                                .map(|(n, s)| Some((n.clone(), self.written(s, doc, old, stack)?)))
1432                                .collect::<Option<_>>()?,
1433                        ),
1434                        (
1435                            "prefixItems" | "oneOf" | "anyOf" | "items" | "additionalProperties",
1436                            sub,
1437                        ) => self.written(sub, doc, old, stack)?,
1438                        (_, x) => x.clone(),
1439                    };
1440                    out.insert(k.clone(), x);
1441                }
1442                Some(Value::Object(out))
1443            }
1444            x => Some(x.clone()),
1445        }
1446    }
1447
1448    #[allow(clippy::too_many_arguments)]
1449    fn compare(
1450        &self,
1451        so: &Value,
1452        doc_o: &'a Value,
1453        sn: &Value,
1454        doc_n: &'a Value,
1455        at: &str,
1456        seen: &mut BTreeSet<(String, String)>,
1457        v: &mut Verdict,
1458    ) {
1459        let key = (
1460            String::from_utf8(jcs(so)).unwrap_or_default(),
1461            String::from_utf8(jcs(sn)).unwrap_or_default(),
1462        );
1463        if !seen.insert(key) {
1464            return;
1465        }
1466        let (Some((o, doc_o)), Some((n, doc_n))) =
1467            (self.deref(so, doc_o, true), self.deref(sn, doc_n, false))
1468        else {
1469            v.push(
1470                Class::Review,
1471                "schema_unreadable",
1472                at,
1473                "a `$ref` resolves to nothing in its revision",
1474            );
1475            return;
1476        };
1477        // A nullable form is compared as its reading (spec §7.3, 0.7), unless
1478        // the other side holds an `anyOf` that is not one: two `anyOf`s that
1479        // are not both nullables stay undecided, compared as written.
1480        let (ro, rn) = (
1481            self.nullable(&o, doc_o, true),
1482            self.nullable(&n, doc_n, false),
1483        );
1484        let other_anyof =
1485            |s: &Value, read: &Option<(Value, &Value)>| read.is_none() && s.get("anyOf").is_some();
1486        let as_written =
1487            (ro.is_some() && other_anyof(&n, &rn)) || (rn.is_some() && other_anyof(&o, &ro));
1488        let ((o, doc_o), (n, doc_n)) = if as_written {
1489            ((o, doc_o), (n, doc_n))
1490        } else {
1491            (ro.unwrap_or((o, doc_o)), rn.unwrap_or((n, doc_n)))
1492        };
1493        let (o, n) = (&o, &n);
1494        // A boolean schema (`true` accepts anything, `false` nothing) is not
1495        // compared keyword by keyword: any change to or from one is review.
1496        if o.is_boolean() || n.is_boolean() {
1497            if o != n {
1498                v.push(
1499                    Class::Review,
1500                    "boolean_schema_changed",
1501                    at,
1502                    "a boolean schema changed",
1503                );
1504            }
1505            return;
1506        }
1507        if types(o) != types(n) {
1508            v.push(
1509                Class::Breaking,
1510                "type_changed",
1511                at,
1512                format!("{:?} → {:?}", types(o), types(n)),
1513            );
1514            return;
1515        }
1516        for k in BOUNDS {
1517            if o.get(*k) != n.get(*k) {
1518                v.push(
1519                    Class::Breaking,
1520                    "bound_changed",
1521                    at,
1522                    format!("`{k}` changed"),
1523                );
1524            }
1525        }
1526        if values(o.get("enum")) != values(n.get("enum")) {
1527            v.push(
1528                Class::Breaking,
1529                "enum_changed",
1530                at,
1531                "a value added or removed",
1532            );
1533        }
1534        if o.get("const") != n.get("const") {
1535            v.push(Class::Breaking, "const_changed", at, "`const` changed");
1536        }
1537        // Undecided keywords: review on any change, breaking on a oneOf
1538        // branch added (spike S7). Compared as written, through their
1539        // `$ref`s (spec §9.8, 0.7): a change to a definition reached only
1540        // from inside one is a change inside it.
1541        for k in ["oneOf", "anyOf", "prefixItems"] {
1542            let written = |s: &Value, doc: &'a Value, old: bool| {
1543                s.get(k).map(|x| self.written(x, doc, old, &mut Vec::new()))
1544            };
1545            let (a, b) = match (written(o, doc_o, true), written(n, doc_n, false)) {
1546                (Some(None), _) | (_, Some(None)) => {
1547                    v.push(
1548                        Class::Review,
1549                        "schema_unreadable",
1550                        at,
1551                        format!("a `$ref` inside `{k}` resolves to nothing in its revision"),
1552                    );
1553                    continue;
1554                }
1555                (a, b) => (a.flatten(), b.flatten()),
1556            };
1557            if a == b {
1558                continue;
1559            }
1560            let grown = k == "oneOf"
1561                && matches!((&a, &b), (Some(Value::Array(x)), Some(Value::Array(y))) if y.len() > x.len());
1562            if grown {
1563                v.push(
1564                    Class::Breaking,
1565                    "oneof_branch_added",
1566                    at,
1567                    "a `oneOf` branch added",
1568                );
1569            } else {
1570                v.push(
1571                    Class::Review,
1572                    "undecided_changed",
1573                    at,
1574                    format!("`{k}` changed"),
1575                );
1576            }
1577        }
1578        // Objects: tolerant readers, writers send only what they declare.
1579        let empty = Map::new();
1580        let po = o
1581            .get("properties")
1582            .and_then(Value::as_object)
1583            .unwrap_or(&empty);
1584        let pn = n
1585            .get("properties")
1586            .and_then(Value::as_object)
1587            .unwrap_or(&empty);
1588        let (ro, rn) = (required(o), required(n));
1589        for (name, so) in po {
1590            let pat = format!("{at}.{name}");
1591            match pn.get(name) {
1592                Some(sn) => {
1593                    if ro.contains(name) != rn.contains(name) {
1594                        v.push(
1595                            Class::Breaking,
1596                            "required_changed",
1597                            &pat,
1598                            "optional ↔ required",
1599                        );
1600                    }
1601                    self.compare(so, doc_o, sn, doc_n, &pat, seen, v);
1602                }
1603                None if ro.contains(name) => {
1604                    v.push(
1605                        Class::Breaking,
1606                        "required_removed",
1607                        &pat,
1608                        "a required property removed",
1609                    );
1610                }
1611                None => {}
1612            }
1613        }
1614        for name in pn.keys() {
1615            if !po.contains_key(name) && rn.contains(name) {
1616                v.push(
1617                    Class::Breaking,
1618                    "required_added",
1619                    &format!("{at}.{name}"),
1620                    "a required property added",
1621                );
1622            }
1623        }
1624        // A required name with no property on either side still binds:
1625        // the member must be present, whatever its value.
1626        for name in ro.symmetric_difference(&rn) {
1627            if po.contains_key(name) || pn.contains_key(name) {
1628                continue;
1629            }
1630            let rule = if rn.contains(name) {
1631                "required_added"
1632            } else {
1633                "required_removed"
1634            };
1635            v.push(
1636                Class::Breaking,
1637                rule,
1638                &format!("{at}.{name}"),
1639                "a required name without a property",
1640            );
1641        }
1642        // Members: a schema on both sides is compared; a boolean or absent
1643        // one on both is open or closed, which tolerant readers ignore; a
1644        // schema on one side only is review (a map closed, or array items
1645        // constrained).
1646        for k in ["items", "additionalProperties"] {
1647            match (o.get(k), n.get(k)) {
1648                (Some(a @ Value::Object(_)), Some(b @ Value::Object(_))) => {
1649                    self.compare(a, doc_o, b, doc_n, &format!("{at}.{k}"), seen, v);
1650                }
1651                (Some(Value::Object(_)), _) | (_, Some(Value::Object(_))) => {
1652                    v.push(
1653                        Class::Review,
1654                        "members_changed",
1655                        at,
1656                        format!("`{k}` gained or lost a schema"),
1657                    );
1658                }
1659                _ => {}
1660            }
1661        }
1662    }
1663}
1664
1665/// The retention rule's identity check (spec §9.7): the same canonical form
1666/// once schema ids are replaced by artifact names, and the same artifacts
1667/// once protobuf descriptor sets are normalized.
1668#[must_use]
1669pub fn same_revision(a: &Revision, b: &Revision) -> bool {
1670    let named = |r: &Revision| -> Option<(Value, BTreeMap<String, Vec<u8>>)> {
1671        let mut by_name = BTreeMap::new();
1672        let mut ids = BTreeMap::new();
1673        for s in r.canonical["schemas"].as_array()? {
1674            let (id, name) = (s["id"].as_str()?, s["name"].as_str()?);
1675            let key = format!("{}:{name}", s["kind"].as_str()?);
1676            let bytes = match r.schemas.get(id)? {
1677                Schema::Protobuf(b) => normalize_fds(b)?,
1678                Schema::Json(v) => jcs(v),
1679            };
1680            by_name.insert(key.clone(), bytes);
1681            ids.insert(id.to_owned(), key);
1682        }
1683        let mut c = r.canonical.clone();
1684        c["schemas"] = Value::Null;
1685        replace_ids(&mut c, &ids);
1686        Some((c, by_name))
1687    };
1688    match (named(a), named(b)) {
1689        (Some(x), Some(y)) => x == y,
1690        _ => false,
1691    }
1692}
1693
1694fn replace_ids(v: &mut Value, ids: &BTreeMap<String, String>) {
1695    match v {
1696        Value::String(s) => {
1697            if let Some(k) = ids.get(s.as_str()) {
1698                *s = k.clone();
1699            }
1700        }
1701        Value::Array(a) => a.iter_mut().for_each(|x| replace_ids(x, ids)),
1702        Value::Object(m) => m.values_mut().for_each(|x| replace_ids(x, ids)),
1703        _ => {}
1704    }
1705}
1706
1707/// A `FileDescriptorSet` with source info dropped and every `json_name`
1708/// equal to its default dropped, re-encoded.
1709fn normalize_fds(bytes: &[u8]) -> Option<Vec<u8>> {
1710    let mut set = prost_types::FileDescriptorSet::decode(bytes).ok()?;
1711    for f in &mut set.file {
1712        f.source_code_info = None;
1713        for m in &mut f.message_type {
1714            normalize_message(m);
1715        }
1716    }
1717    Some(set.encode_to_vec())
1718}
1719
1720fn normalize_message(m: &mut prost_types::DescriptorProto) {
1721    for f in &mut m.field {
1722        if f.json_name.as_deref() == Some(default_json_name(f.name()).as_str()) {
1723            f.json_name = None;
1724        }
1725    }
1726    for n in &mut m.nested_type {
1727        normalize_message(n);
1728    }
1729}
1730
1731/// protoc's default JSON name: underscores removed, the next letter
1732/// uppercased.
1733fn default_json_name(name: &str) -> String {
1734    let mut out = String::with_capacity(name.len());
1735    let mut up = false;
1736    for c in name.chars() {
1737        if c == '_' {
1738            up = true;
1739        } else if up {
1740            out.extend(c.to_uppercase());
1741            up = false;
1742        } else {
1743            out.push(c);
1744        }
1745    }
1746    out
1747}
1748
1749#[cfg(test)]
1750mod tests {
1751    use std::path::Path;
1752
1753    use serde_json::json;
1754
1755    use super::*;
1756    use crate::contract::load_str;
1757
1758    /// A one-type revision over a JSON Schema document, as the `compat/`
1759    /// fixtures wrap theirs.
1760    fn rev(dir: &Path, doc: &Value) -> Revision {
1761        std::fs::write(dir.join("t.json"), doc.to_string()).unwrap();
1762        let src = "[interface]\nname = \"m\"\nmajor = 1\nminor = 0\n[schemas]\njsonschema = [\"t.json\"]\n\
1763                   [resources.s]\nkind = \"state\"\ntype = \"json:T\"\n";
1764        let l = load_str(src, dir, None);
1765        Revision::of(&l.contract.unwrap_or_else(|| panic!("{}", l.report)))
1766    }
1767
1768    fn class(old: &Value, new: &Value) -> &'static str {
1769        static N: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
1770        let n = N.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1771        let dir = std::env::temp_dir().join(format!("zk2-compat-{}-{n}", std::process::id()));
1772        std::fs::create_dir_all(&dir).unwrap();
1773        let (o, n) = (rev(&dir, old), rev(&dir, new));
1774        std::fs::remove_dir_all(&dir).unwrap();
1775        compare(&o, &n).class().as_str()
1776    }
1777
1778    fn doc(t: &Value) -> Value {
1779        json!({"$defs": {"T": t, "U": {"type": "integer"}}})
1780    }
1781
1782    #[test]
1783    fn keywords_beside_a_ref_are_compared() {
1784        let a = doc(&json!({"type": "object", "properties": {"n": {"$ref": "#/$defs/U"}}}));
1785        let b = doc(
1786            &json!({"type": "object", "properties": {"n": {"$ref": "#/$defs/U", "maximum": 3}}}),
1787        );
1788        assert_eq!(class(&a, &b), "breaking");
1789        assert_eq!(class(&b, &b), "compatible");
1790        let inline =
1791            doc(&json!({"type": "object", "properties": {"n": {"type": "integer", "maximum": 3}}}));
1792        assert_eq!(class(&b, &inline), "compatible");
1793    }
1794
1795    #[test]
1796    fn boolean_schemas_are_review() {
1797        let t = |p: Value| doc(&json!({"type": "object", "properties": {"p": p}}));
1798        assert_eq!(class(&t(json!(true)), &t(json!(false))), "review");
1799        assert_eq!(class(&t(json!(true)), &t(json!({}))), "review");
1800        assert_eq!(class(&t(json!(false)), &t(json!(false))), "compatible");
1801    }
1802
1803    #[test]
1804    fn a_required_name_without_a_property_binds() {
1805        let t = |r: Value| doc(&json!({"type": "object", "required": r}));
1806        assert_eq!(class(&t(json!(["a"])), &t(json!([]))), "breaking");
1807        assert_eq!(class(&t(json!([])), &t(json!(["a"]))), "breaking");
1808        assert_eq!(class(&t(json!(["a"])), &t(json!(["a"]))), "compatible");
1809    }
1810
1811    /// Spec §9.8 (0.6, F-62): a `$ref` that resolves to nothing in its
1812    /// revision, which only a non-conforming builder writes, is unreadable
1813    /// (review), never resolved in the referencing document instead.
1814    #[test]
1815    fn a_ref_that_resolves_to_nothing_is_unreadable() {
1816        let dir = std::env::temp_dir().join(format!("zk2-compat-dangling-{}", std::process::id()));
1817        std::fs::create_dir_all(&dir).unwrap();
1818        let ok = doc(&json!({"type": "object", "properties": {"n": {"$ref": "#/$defs/U"}}}));
1819        let old = rev(&dir, &ok);
1820        std::fs::remove_dir_all(&dir).unwrap();
1821        for dangling in ["u.json#/$defs/U", "#/$defs/Gone"] {
1822            let mut new = old.clone();
1823            for s in new.schemas.values_mut() {
1824                if let Schema::Json(v) = s {
1825                    v["$defs"]["T"]["properties"]["n"]["$ref"] = json!(dangling);
1826                }
1827            }
1828            let v = compare(&old, &new);
1829            assert_eq!(v.class().as_str(), "review", "{dangling}");
1830            assert!(
1831                v.findings.iter().all(|f| f.rule == "schema_unreadable"),
1832                "{dangling}: {:?}",
1833                v.findings
1834            );
1835        }
1836    }
1837
1838    #[test]
1839    fn property_names_inside_oneof_are_not_annotations() {
1840        let t = |ty: &str| {
1841            doc(&json!({"oneOf": [{"type": "object", "properties": {"title": {"type": ty}}}]}))
1842        };
1843        assert_eq!(class(&t("string"), &t("integer")), "review");
1844        let d = |text: &str| doc(&json!({"oneOf": [{"type": "string", "description": text}]}));
1845        assert_eq!(class(&d("a"), &d("b")), "compatible");
1846    }
1847
1848    /// A one-property object whose property `p` is `schema`, beside the
1849    /// definitions `I` (an object) and `E` (a string enum).
1850    fn with_p(schema: &Value, i: &Value, e: &Value) -> Value {
1851        json!({"$defs": {
1852            "T": {"type": "object", "properties": {"p": schema}},
1853            "I": i,
1854            "E": e,
1855        }})
1856    }
1857
1858    /// Spec §7.3 and §9.8 (0.7, C-1): a nullable's two spellings are one
1859    /// type, and a change inside its S is classified by the decided rules,
1860    /// through its `$ref`.
1861    #[test]
1862    fn a_nullable_is_one_type_in_either_spelling() {
1863        let i =
1864            json!({"type": "object", "properties": {"x": {"type": "integer"}}, "required": ["x"]});
1865        let e = json!({"type": "string", "enum": ["a", "b"]});
1866        let t = |p: Value| with_p(&p, &i, &e);
1867        let nul = json!({"type": "null"});
1868        let ty = t(json!({"type": ["integer", "null"], "minimum": 0}));
1869        let any = t(json!({"anyOf": [{"type": "integer", "minimum": 0}, nul]}));
1870        let any_rev = t(json!({"anyOf": [nul, {"type": "integer", "minimum": 0}]}));
1871        assert_eq!(class(&ty, &any), "compatible");
1872        assert_eq!(class(&any, &ty), "compatible");
1873        assert_eq!(class(&any, &any_rev), "compatible");
1874        // S's changes are decided, not review.
1875        let num = t(json!({"anyOf": [{"type": "number", "minimum": 0}, nul]}));
1876        assert_eq!(class(&any, &num), "breaking");
1877        let looser =
1878            t(json!({"anyOf": [{"type": "integer", "minimum": 0, "description": "d"}, nul]}));
1879        assert_eq!(class(&any, &looser), "compatible");
1880        // Dropping the null is a type change.
1881        assert_eq!(
1882            class(&any, &t(json!({"type": "integer", "minimum": 0}))),
1883            "breaking"
1884        );
1885        // Through a `$ref`: a change in the target is seen.
1886        let r = |i: &Value| with_p(&json!({"anyOf": [{"$ref": "#/$defs/I"}, nul]}), i, &e);
1887        let retyped =
1888            json!({"type": "object", "properties": {"x": {"type": "string"}}, "required": ["x"]});
1889        assert_eq!(class(&r(&i), &r(&retyped)), "breaking");
1890        let widened = json!({"type": "object", "properties": {"x": {"type": "integer"}, "y": {"type": "string"}}, "required": ["x"]});
1891        assert_eq!(class(&r(&i), &r(&widened)), "compatible");
1892        // An enum's reading accepts null too; one that does not is another type.
1893        let er = t(json!({"anyOf": [{"$ref": "#/$defs/E"}, nul]}));
1894        let with_null = t(json!({"type": ["string", "null"], "enum": ["a", "b", null]}));
1895        let without = t(json!({"type": ["string", "null"], "enum": ["a", "b"]}));
1896        assert_eq!(class(&er, &with_null), "compatible");
1897        assert_eq!(class(&er, &without), "breaking");
1898    }
1899
1900    /// Spec §9.8 (0.7): against an `anyOf` that is not a nullable, both stay
1901    /// undecided (the `anyof-add-branch` fixture's case), and an S without a
1902    /// reading is compared as written.
1903    #[test]
1904    fn a_nullable_beside_another_anyof_stays_undecided() {
1905        let (i, e) = (json!({"type": "object"}), json!({"type": "string"}));
1906        let t = |p: Value| with_p(&p, &i, &e);
1907        let one = t(json!({"anyOf": [{"type": "integer"}]}));
1908        let two = t(json!({"anyOf": [{"type": "integer"}, {"type": "null"}]}));
1909        assert_eq!(class(&one, &two), "review");
1910        assert_eq!(class(&two, &one), "review");
1911        let konst = t(json!({"anyOf": [{"type": "string", "const": "k"}, {"type": "null"}]}));
1912        let konst2 = t(json!({"anyOf": [{"type": "string", "const": "j"}, {"type": "null"}]}));
1913        assert_eq!(class(&konst, &konst2), "review");
1914    }
1915
1916    /// Spec §9.8 (0.7): inside an undecided keyword, a `$ref` is compared
1917    /// by its target, so a change there is a change inside the keyword; a
1918    /// recursive type ends; a dangling one is unreadable.
1919    #[test]
1920    fn a_ref_inside_an_undecided_keyword_is_followed() {
1921        let t = |body: Value| {
1922            json!({"$defs": {
1923                "T": {"oneOf": [{"type": "object", "properties": {"body": {"$ref": "#/$defs/B"}}}]},
1924                "B": body,
1925            }})
1926        };
1927        let b = json!({"type": "object", "properties": {"x": {"type": "integer"}}});
1928        let b2 = json!({"type": "object", "properties": {"x": {"type": "string"}}});
1929        assert_eq!(class(&t(b.clone()), &t(b.clone())), "compatible");
1930        assert_eq!(class(&t(b.clone()), &t(b2)), "review");
1931        let inline =
1932            json!({"$defs": {"T": {"oneOf": [{"type": "object", "properties": {"body": b}}]}}});
1933        assert_eq!(class(&t(b.clone()), &inline), "compatible");
1934        let tree = |ty: &str| {
1935            json!({"$defs": {"T": {"anyOf": [
1936                {"type": ty},
1937                {"type": "array", "items": {"$ref": "#/$defs/T"}},
1938            ]}}})
1939        };
1940        assert_eq!(class(&tree("integer"), &tree("integer")), "compatible");
1941        assert_eq!(class(&tree("integer"), &tree("string")), "review");
1942
1943        let dir = std::env::temp_dir().join(format!("zk2-compat-oneof-ref-{}", std::process::id()));
1944        std::fs::create_dir_all(&dir).unwrap();
1945        let old = rev(&dir, &t(json!({"type": "integer"})));
1946        std::fs::remove_dir_all(&dir).unwrap();
1947        let mut new = old.clone();
1948        for s in new.schemas.values_mut() {
1949            if let Schema::Json(v) = s {
1950                v["$defs"]["T"]["oneOf"][0]["properties"]["body"]["$ref"] = json!("#/$defs/Gone");
1951            }
1952        }
1953        let v = compare(&old, &new);
1954        assert_eq!(v.class().as_str(), "review");
1955        assert!(
1956            v.findings.iter().all(|f| f.rule == "schema_unreadable"),
1957            "{:?}",
1958            v.findings
1959        );
1960    }
1961
1962    /// A packed enum whose escape toggles reports its values' changes too
1963    /// (#979 B2, review of B1): every change, never the first alone.
1964    #[test]
1965    fn a_packed_enum_reports_every_change() {
1966        let dir = std::env::temp_dir().join(format!("zk2-compat-packed-{}", std::process::id()));
1967        std::fs::create_dir_all(&dir).unwrap();
1968        let rev = |values: &[&str], escape: bool| {
1969            let doc = json!({"types": {"T": {"fields": [
1970                {"name": "m", "type": "enum", "values": values, "escape": escape, "width": 3}
1971            ]}}});
1972            std::fs::write(dir.join("t.json"), doc.to_string()).unwrap();
1973            let src = "[interface]\nname = \"m\"\nmajor = 1\nminor = 0\n[schemas]\npacked = [\"t.json\"]\n\
1974                       [resources.s]\nkind = \"state\"\ntype = \"packed:T\"\n";
1975            let l = load_str(src, &dir, None);
1976            Revision::of(&l.contract.unwrap_or_else(|| panic!("{}", l.report)))
1977        };
1978        let old = rev(&["off", "on", "auto"], false);
1979        let new = rev(&["off", "up", "auto", "eco"], true);
1980        std::fs::remove_dir_all(&dir).unwrap();
1981        let v = compare(&old, &new);
1982        assert_eq!(v.class().as_str(), "breaking");
1983        let said: Vec<(&str, &str)> = v
1984            .findings
1985            .iter()
1986            .map(|f| (f.rule, f.detail.as_str()))
1987            .collect();
1988        assert!(
1989            said.contains(&("enum_changed", "the escape toggled")),
1990            "{said:?}"
1991        );
1992        assert!(
1993            said.contains(&("enum_value_renamed", "\"on\" renamed \"up\"")),
1994            "{said:?}"
1995        );
1996        assert!(
1997            said.iter()
1998                .any(|(r, d)| *r == "enum_changed" && d.contains("added or removed")),
1999            "{said:?}"
2000        );
2001    }
2002}