Skip to main content

bynk_check/
contract_compat.rs

1//! #2485: is a service-contract change compatible, or breaking?
2//!
3//! [`crate::contract`] reduces a service to a canonical text and an FNV-1a hash,
4//! and the deploy gate (ADR 0491) counts any difference as skew. A hash says
5//! *whether* a contract moved, never *how*. This module keeps the structure the
6//! hash throws away, so the toolchain can say whether a caller compiled against
7//! one contract still works against a callee providing another, and why.
8//!
9//! Three pieces, all here so the deploy gate and the editor share one answer:
10//!
11//! 1. [`ServiceShape`]: the contract as a tree, built by the same walk as
12//!    [`crate::contract::service_normal_form`] and rendering back to exactly
13//!    that text ([`ServiceShape::normal_form`]), so a stored shape can be
14//!    checked against the hash it was recorded with.
15//! 2. [`ServiceShape::to_text`] / [`ServiceShape::from_text`]: a compact,
16//!    unambiguous text for the ledger and the build manifest. The normal form
17//!    itself cannot be parsed back (`AgeInt where Positive` does not say where
18//!    the type's name stops and its base begins), so the ledger keeps this
19//!    beside the hash instead.
20//! 3. [`check_call`]: the classifier.
21//!
22//! ## The rule
23//!
24//! Compatibility is about **values on the wire**, so the rules are the wire
25//! format's own (`reference/wire-format.md`): a record is an object keyed by
26//! field name, an unknown key is ignored, a missing `Option` field is `None`,
27//! a bare value is accepted where an `Option` is expected, and a multi-argument
28//! call is an object keyed by parameter name. A request flows caller to callee
29//! and a response callee to caller; in both, the receiver must be able to
30//! decode everything the sender can produce. That one question,
31//! `flows(sender, receiver)`, is asked of the request with the caller as sender
32//! and of the response with the callee as sender, which is how "add an optional
33//! request field" is compatible and "add a response variant" is breaking from a
34//! single definition.
35//!
36//! The classifier errs towards **breaking**. A field missing from the sender
37//! is compatible only when it is an `Option` or the receiver's field declares a
38//! default (#2689: the stored shape marks it; a shape recorded before the
39//! marker reads as having none). A wrong
40//! "compatible" lets a breaking deploy through; a wrong "breaking" only names a
41//! skew the gate already refuses.
42
43use std::collections::HashMap;
44use std::fmt::Write as _;
45use std::sync::Arc;
46
47use bynk_syntax::ast::{TypeBody, TypeDecl, TypeRef};
48
49use crate::contract::canon_pred_set;
50use crate::entailment::unmet;
51use crate::resolver::CrossContextService;
52
53/// One type as it appears on the wire. Mirrors the `Contract` rendering of
54/// [`crate::contract`]: named types expand structurally, record fields and sum
55/// variants are sorted, predicates are a sorted set, and an opaque type's
56/// predicate is left out.
57#[derive(Debug, Clone, PartialEq, Eq)]
58pub enum Shape {
59    Base(String),
60    Unit,
61    List(Box<Shape>),
62    /// K6a (#2596): a `Set`, whose element must match exactly, as a `Map` key
63    /// must.
64    Set(Box<Shape>),
65    Option(Box<Shape>),
66    Result(Box<Shape>, Box<Shape>),
67    Map(Box<Shape>, Box<Shape>),
68    HttpResult(Box<Shape>),
69    /// A name with nothing to expand: a runtime-known type, or one outside the
70    /// callee's table.
71    Named(String),
72    /// A back-reference to an enclosing named type, closing a recursive shape.
73    Ref(String),
74    Record {
75        name: String,
76        fields: Vec<Field>,
77    },
78    Sum {
79        name: String,
80        variants: Vec<Variant>,
81    },
82    Refined {
83        name: String,
84        base: String,
85        preds: Vec<String>,
86    },
87    Opaque {
88        name: String,
89        base: String,
90    },
91    /// A generic instantiation: `head` is the declaration expanded over the
92    /// arguments, which are kept so the form renders as the normal form does.
93    App {
94        head: Box<Shape>,
95        args: Vec<Shape>,
96    },
97}
98
99#[derive(Debug, Clone, PartialEq, Eq)]
100pub struct Field {
101    pub name: String,
102    pub ty: Shape,
103    /// The field's own inline refinement (#1969), as a sorted predicate set.
104    pub preds: Vec<String>,
105    /// #2689: the field declares a default (`f: T = expr`), so a body without
106    /// its key decodes (ADR 0676 C). Part of the stored shape text, never of
107    /// the normal form or the hash: a default is not hashed. Text recorded
108    /// before the marker existed reads `false`, which errs towards breaking.
109    pub defaulted: bool,
110}
111
112#[derive(Debug, Clone, PartialEq, Eq)]
113pub struct Variant {
114    pub name: String,
115    /// The variant's payload fields, keyed by name on the wire and sorted like
116    /// a record's. Inline refinements are not part of a payload's form.
117    pub payload: Vec<Field>,
118}
119
120/// One `on call` service contract as a tree.
121#[derive(Debug, Clone, PartialEq, Eq)]
122pub struct ServiceShape {
123    pub name: String,
124    pub params: Vec<(String, Shape)>,
125    pub ret: Shape,
126}
127
128impl ServiceShape {
129    /// Build the shape of `svc` in the callee's own namespace (`types`), as
130    /// [`crate::contract::service_normal_form`] does.
131    pub fn of(svc: &CrossContextService, types: &HashMap<String, Arc<TypeDecl>>) -> Self {
132        let build = |t: &TypeRef| shape_of(t, types, &mut Vec::new(), &HashMap::new());
133        ServiceShape {
134            name: svc.name.clone(),
135            params: svc
136                .params
137                .iter()
138                .map(|(n, t)| (n.clone(), build(t)))
139                .collect(),
140            ret: build(&svc.return_type),
141        }
142    }
143
144    /// The canonical normal form, byte-for-byte what
145    /// [`crate::contract::service_normal_form`] renders for the same service.
146    pub fn normal_form(&self) -> String {
147        let mut out = format!("{}(", self.name);
148        for (i, (name, ty)) in self.params.iter().enumerate() {
149            if i > 0 {
150                out.push_str(", ");
151            }
152            let _ = write!(out, "{name}: {}", render(ty));
153        }
154        let _ = write!(out, ") -> {}", render(&self.ret));
155        out
156    }
157
158    /// The hash of [`ServiceShape::normal_form`], i.e. the service's contract
159    /// hash.
160    pub fn hash(&self) -> String {
161        crate::contract::contract_hash(&self.normal_form())
162    }
163
164    /// The ledger and manifest text. Round-trips through
165    /// [`ServiceShape::from_text`].
166    pub fn to_text(&self) -> String {
167        let mut args = vec![Node::Str(self.name.clone())];
168        for (name, ty) in &self.params {
169            args.push(Node::call(
170                "P",
171                vec![Node::Str(name.clone()), shape_node(ty)],
172            ));
173        }
174        args.push(Node::call("Ret", vec![shape_node(&self.ret)]));
175        let mut out = String::new();
176        Node::call("Svc", args).write(&mut out);
177        out
178    }
179
180    /// Read [`ServiceShape::to_text`] back. `None` for anything else: a stored
181    /// shape that does not parse is treated as absent, never guessed at.
182    pub fn from_text(text: &str) -> Option<Self> {
183        let node = Node::parse(text)?;
184        let Node::Call(head, mut args) = node else {
185            return None;
186        };
187        if head != "Svc" || args.len() < 2 {
188            return None;
189        }
190        let Node::Str(name) = args.remove(0) else {
191            return None;
192        };
193        let Node::Call(ret_head, mut ret_args) = args.pop()? else {
194            return None;
195        };
196        if ret_head != "Ret" || ret_args.len() != 1 {
197            return None;
198        }
199        let ret = node_shape(&ret_args.remove(0))?;
200        let mut params = Vec::new();
201        for p in args {
202            let Node::Call(h, mut a) = p else {
203                return None;
204            };
205            if h != "P" || a.len() != 2 {
206                return None;
207            }
208            let ty = node_shape(&a.pop()?)?;
209            let Node::Str(pname) = a.pop()? else {
210                return None;
211            };
212            params.push((pname, ty));
213        }
214        Some(ServiceShape { name, params, ret })
215    }
216
217    /// A stored shape is trusted only if it renders to the form that hashes to
218    /// the hash the ledger recorded beside it. A stale, hand-edited or
219    /// differently-versioned entry then reads as no shape at all.
220    pub fn from_text_checked(text: &str, hash: &str) -> Option<Self> {
221        Self::from_text(text).filter(|s| s.hash() == hash)
222    }
223}
224
225/// A context's own `on call` shapes as ledger text, keyed by service name —
226/// the structured twin of [`crate::contract::own_contract_hashes`], built from
227/// the same projection and the same table so each text hashes to the hash
228/// recorded beside it.
229pub fn own_contract_shapes(
230    table: &crate::symbols::UnitTable,
231    own_types: &HashMap<String, Arc<TypeDecl>>,
232) -> std::collections::BTreeMap<String, String> {
233    table
234        .services
235        .iter()
236        .filter_map(|(name, decl)| {
237            let svc = crate::resolver::cross_context_service_for(name, decl)?;
238            Some((name.clone(), ServiceShape::of(&svc, own_types).to_text()))
239        })
240        .collect()
241}
242
243/// #2554: what a callee accepts of the older contracts a lock lists for one
244/// service.
245#[derive(Debug, Default, PartialEq, Eq)]
246pub struct Accepted {
247    /// The hashes the callee accepts besides its own, in lock order, each the
248    /// hash of a kept shape.
249    pub hashes: Vec<String>,
250    /// The shape texts kept, parallel to `hashes`.
251    pub kept: Vec<String>,
252    /// The entries left out, each with the reason.
253    pub rejected: Vec<(String, String)>,
254}
255
256/// Decide which of `older` (shape texts from the contracts lock) the callee
257/// whose service has `current` accepts.
258///
259/// Each entry is checked against `current` itself with [`check_call`]: it is
260/// kept only if a caller compiled against it still works against `current`.
261/// Compatibility is never carried through intermediate versions, so an entry
262/// that was compatible with the contract before this one is dropped if it is
263/// not compatible with this one. An entry for another service, one that does
264/// not parse, or one equal to `current` is left out (the last silently: the
265/// callee already accepts its own hash).
266pub fn accepted_for(current: &ServiceShape, older: &[String]) -> Accepted {
267    let mut out = Accepted::default();
268    for text in older {
269        let Some(old) = ServiceShape::from_text(text) else {
270            out.rejected.push((
271                text.clone(),
272                "it is not a contract shape this version can read".into(),
273            ));
274            continue;
275        };
276        if old.name != current.name {
277            out.rejected.push((
278                text.clone(),
279                format!(
280                    "it is the contract of `{}`, not `{}`",
281                    old.name, current.name
282                ),
283            ));
284            continue;
285        }
286        let hash = old.hash();
287        if hash == current.hash() || out.hashes.contains(&hash) {
288            continue;
289        }
290        let verdict = check_call(&old, current);
291        if verdict.verdict == Verdict::Breaking {
292            let why = verdict
293                .breaking()
294                .next()
295                .map(|f| format!("{}: {}", f.path, f.message))
296                .unwrap_or_default();
297            out.rejected
298                .push((text.clone(), format!("callers on it would break ({why})")));
299            continue;
300        }
301        out.hashes.push(hash);
302        out.kept.push(text.clone());
303    }
304    out
305}
306
307/// #2554: the older contracts one context's services accept, from the contracts
308/// lock, with what was left out.
309#[derive(Debug, Default, PartialEq, Eq)]
310pub struct ContextAccepted {
311    /// Service to the hashes it accepts besides its own. A service accepting
312    /// none is absent.
313    pub hashes: std::collections::BTreeMap<String, Vec<String>>,
314    /// `(service, why)` for each lock entry left out.
315    pub stale: Vec<(String, String)>,
316    /// `(service, count)` for each service accepting more than `cap`.
317    pub oversized: Vec<(String, usize)>,
318}
319
320/// Which older contracts each of a context's `on call` services accepts.
321/// `older(service)` is the lock's shape texts for it. `cap` is how many a
322/// service may keep before it is reported.
323pub fn own_accepted<'a>(
324    table: &crate::symbols::UnitTable,
325    own_types: &HashMap<String, Arc<TypeDecl>>,
326    older: impl Fn(&str) -> &'a [String],
327    cap: usize,
328) -> ContextAccepted {
329    let mut out = ContextAccepted::default();
330    for (name, decl) in &table.services {
331        let texts = older(name);
332        if texts.is_empty() {
333            continue;
334        }
335        let Some(svc) = crate::resolver::cross_context_service_for(name, decl) else {
336            for _ in texts {
337                out.stale.push((
338                    name.clone(),
339                    "the service is no longer an `on call` service".into(),
340                ));
341            }
342            continue;
343        };
344        let current = ServiceShape::of(&svc, own_types);
345        let accepted = accepted_for(&current, texts);
346        for (_, why) in accepted.rejected {
347            out.stale.push((name.clone(), why));
348        }
349        if accepted.hashes.len() > cap {
350            out.oversized.push((name.clone(), accepted.hashes.len()));
351        }
352        if !accepted.hashes.is_empty() {
353            out.hashes.insert(name.clone(), accepted.hashes);
354        }
355    }
356    out
357}
358
359// ---- building ---------------------------------------------------------------
360
361/// The tree twin of `contract::canon_type_in` in `Mode::Contract`. Keep the two
362/// in step: [`ServiceShape::normal_form`] is tested against the real normal
363/// form over every type former, which fails if they drift.
364fn shape_of(
365    t: &TypeRef,
366    types: &HashMap<String, Arc<TypeDecl>>,
367    seen: &mut Vec<String>,
368    subst: &HashMap<String, Shape>,
369) -> Shape {
370    let mut go = |t: &TypeRef| shape_of(t, types, seen, subst);
371    match t {
372        TypeRef::Base(b, _) => Shape::Base(b.name().to_string()),
373        TypeRef::Unit(_) => Shape::Unit,
374        TypeRef::Effect(inner, _) => go(inner),
375        TypeRef::List(a, _) => Shape::List(Box::new(go(a))),
376        TypeRef::Set(a, _) => Shape::Set(Box::new(go(a))),
377        TypeRef::Option(a, _) => Shape::Option(Box::new(go(a))),
378        TypeRef::Result(a, b, _) => Shape::Result(Box::new(go(a)), Box::new(go(b))),
379        TypeRef::Map(k, v, _) => Shape::Map(Box::new(go(k)), Box::new(go(v))),
380        TypeRef::App { name, args, .. } => {
381            let inner: Vec<Shape> = args.iter().map(&mut go).collect();
382            let bound: HashMap<String, Shape> = types
383                .get(&name.name)
384                .map(|d| {
385                    d.type_params
386                        .iter()
387                        .zip(&inner)
388                        .map(|(p, a)| (p.name.name.clone(), a.clone()))
389                        .collect()
390                })
391                .unwrap_or_default();
392            let head = named_shape(&name.name, types, seen, &bound);
393            Shape::App {
394                head: Box::new(head),
395                args: inner,
396            }
397        }
398        TypeRef::Named(id) => match subst.get(&id.name) {
399            Some(bound) => bound.clone(),
400            None => named_shape(&id.name, types, seen, subst),
401        },
402        TypeRef::HttpResult(a, _) => Shape::HttpResult(Box::new(go(a))),
403        TypeRef::ValidationError(_) => Shape::Named("ValidationError".into()),
404        TypeRef::DecodeError(_) => Shape::Named("DecodeError".into()),
405        TypeRef::QueueResult(_) => Shape::Named("QueueResult".into()),
406        TypeRef::Asset(_) => Shape::Named("Asset".into()),
407        TypeRef::RequestHeaders(_) => Shape::Named("RequestHeaders".into()),
408        TypeRef::RequestQuery(_) => Shape::Named("RequestQuery".into()),
409        TypeRef::RequestCookies(_) => Shape::Named("RequestCookies".into()),
410        TypeRef::TokenClaims(_) => Shape::Named("TokenClaims".into()),
411        TypeRef::BoundaryRejection(_) => Shape::Named("BoundaryRejection".into()),
412        TypeRef::Fn(..)
413        | TypeRef::Query(..)
414        | TypeRef::Stream(..)
415        | TypeRef::Connection(..)
416        | TypeRef::History(..) => Shape::Named("<non-boundary>".into()),
417    }
418}
419
420fn named_shape(
421    name: &str,
422    types: &HashMap<String, Arc<TypeDecl>>,
423    seen: &mut Vec<String>,
424    subst: &HashMap<String, Shape>,
425) -> Shape {
426    if seen.iter().any(|n| n == name) {
427        return Shape::Ref(name.to_string());
428    }
429    let Some(decl) = types.get(name) else {
430        return Shape::Named(name.to_string());
431    };
432    seen.push(name.to_string());
433    let shape = match &decl.body {
434        TypeBody::Record(r) => {
435            let mut fields: Vec<Field> = r
436                .fields
437                .iter()
438                .map(|f| Field {
439                    name: f.name.name.clone(),
440                    ty: shape_of(&f.type_ref, types, seen, subst),
441                    preds: f
442                        .refinement
443                        .as_ref()
444                        .map(canon_pred_set)
445                        .unwrap_or_default(),
446                    defaulted: f.init.is_some(),
447                })
448                .collect();
449            fields.sort_by_cached_key(render_field);
450            Shape::Record {
451                name: name.to_string(),
452                fields,
453            }
454        }
455        TypeBody::Sum(s) => {
456            let mut variants: Vec<Variant> = s
457                .variants
458                .iter()
459                .map(|v| Variant {
460                    name: v.name.name.clone(),
461                    payload: v
462                        .payload
463                        .iter()
464                        .map(|p| Field {
465                            name: p.name.name.clone(),
466                            ty: shape_of(&p.type_ref, types, seen, subst),
467                            preds: Vec::new(),
468                            defaulted: false,
469                        })
470                        .collect(),
471                })
472                .collect();
473            for v in &mut variants {
474                v.payload.sort_by_cached_key(render_field);
475            }
476            variants.sort_by_cached_key(render_variant);
477            Shape::Sum {
478                name: name.to_string(),
479                variants,
480            }
481        }
482        TypeBody::Refined {
483            base, refinement, ..
484        } => Shape::Refined {
485            name: name.to_string(),
486            base: base.name().to_string(),
487            preds: refinement.as_ref().map(canon_pred_set).unwrap_or_default(),
488        },
489        TypeBody::Opaque { base, .. } => Shape::Opaque {
490            name: name.to_string(),
491            base: base.name().to_string(),
492        },
493    };
494    seen.pop();
495    shape
496}
497
498// ---- rendering the normal form ------------------------------------------------
499
500fn render_field(f: &Field) -> String {
501    let ty = render(&f.ty);
502    if f.preds.is_empty() {
503        format!("{}: {ty}", f.name)
504    } else {
505        format!("{}: {ty} where {}", f.name, f.preds.join(", "))
506    }
507}
508
509fn render_variant(v: &Variant) -> String {
510    if v.payload.is_empty() {
511        v.name.clone()
512    } else {
513        // `named_shape` sorts a payload by this same text and a parsed shape is
514        // checked against its hash, so it is rendered in place.
515        let payload: Vec<String> = v.payload.iter().map(render_field).collect();
516        format!("{}({})", v.name, payload.join(", "))
517    }
518}
519
520fn render(s: &Shape) -> String {
521    match s {
522        Shape::Base(b) => b.clone(),
523        Shape::Unit => "()".to_string(),
524        Shape::List(a) => format!("List[{}]", render(a)),
525        Shape::Set(a) => format!("Set[{}]", render(a)),
526        Shape::Option(a) => format!("Option[{}]", render(a)),
527        Shape::Result(a, b) => format!("Result[{}, {}]", render(a), render(b)),
528        Shape::Map(k, v) => format!("Map[{}, {}]", render(k), render(v)),
529        Shape::HttpResult(a) => format!("HttpResult[{}]", render(a)),
530        Shape::Named(n) => n.clone(),
531        Shape::Ref(n) => format!("@{n}"),
532        Shape::Record { name, fields } => {
533            let mut fs: Vec<String> = fields.iter().map(render_field).collect();
534            fs.sort();
535            format!("{name}{{{}}}", fs.join(", "))
536        }
537        Shape::Sum { name, variants } => {
538            let mut vs: Vec<String> = variants.iter().map(render_variant).collect();
539            vs.sort();
540            format!("{name}|{}", vs.join("|"))
541        }
542        Shape::Refined { name, base, preds } => {
543            if preds.is_empty() {
544                format!("{name}{base} ")
545            } else {
546                format!("{name}{base} where {}", preds.join(", "))
547            }
548        }
549        Shape::Opaque { name, base } => format!("{name}{base} opaque"),
550        Shape::App { head, args } => {
551            let a: Vec<String> = args.iter().map(render).collect();
552            format!("{}[{}]", render(head), a.join(", "))
553        }
554    }
555}
556
557// ---- the text form ------------------------------------------------------------
558
559/// `Head(arg, …)` where an arg is a quoted string or another call. Small enough
560/// to hand-write, and unlike the normal form it has no ambiguous joins.
561#[derive(Debug, Clone, PartialEq, Eq)]
562enum Node {
563    Str(String),
564    Call(String, Vec<Node>),
565}
566
567impl Node {
568    fn call(head: &str, args: Vec<Node>) -> Node {
569        Node::Call(head.to_string(), args)
570    }
571
572    fn write(&self, out: &mut String) {
573        match self {
574            Node::Str(s) => {
575                out.push('"');
576                for c in s.chars() {
577                    if c == '"' || c == '\\' {
578                        out.push('\\');
579                    }
580                    out.push(c);
581                }
582                out.push('"');
583            }
584            Node::Call(head, args) => {
585                out.push_str(head);
586                out.push('(');
587                for (i, a) in args.iter().enumerate() {
588                    if i > 0 {
589                        out.push(',');
590                    }
591                    a.write(out);
592                }
593                out.push(')');
594            }
595        }
596    }
597
598    fn parse(text: &str) -> Option<Node> {
599        let chars: Vec<char> = text.chars().collect();
600        let mut at = 0;
601        let node = Self::parse_at(&chars, &mut at)?;
602        (at == chars.len()).then_some(node)
603    }
604
605    fn parse_at(c: &[char], at: &mut usize) -> Option<Node> {
606        if *c.get(*at)? == '"' {
607            *at += 1;
608            let mut s = String::new();
609            loop {
610                match *c.get(*at)? {
611                    '"' => {
612                        *at += 1;
613                        return Some(Node::Str(s));
614                    }
615                    '\\' => {
616                        *at += 1;
617                        s.push(*c.get(*at)?);
618                    }
619                    ch => s.push(ch),
620                }
621                *at += 1;
622            }
623        }
624        let start = *at;
625        while c.get(*at).is_some_and(|ch| ch.is_ascii_alphanumeric()) {
626            *at += 1;
627        }
628        if start == *at || *c.get(*at)? != '(' {
629            return None;
630        }
631        let head: String = c[start..*at].iter().collect();
632        *at += 1;
633        let mut args = Vec::new();
634        if *c.get(*at)? == ')' {
635            *at += 1;
636            return Some(Node::Call(head, args));
637        }
638        loop {
639            args.push(Self::parse_at(c, at)?);
640            match *c.get(*at)? {
641                ',' => *at += 1,
642                ')' => {
643                    *at += 1;
644                    return Some(Node::Call(head, args));
645                }
646                _ => return None,
647            }
648        }
649    }
650}
651
652fn strs(items: &[String]) -> impl Iterator<Item = Node> + '_ {
653    items.iter().map(|s| Node::Str(s.clone()))
654}
655
656fn field_node(f: &Field) -> Node {
657    let mut fa = vec![Node::Str(f.name.clone()), shape_node(&f.ty)];
658    fa.extend(strs(&f.preds));
659    if f.defaulted {
660        fa.push(Node::call("D", vec![]));
661    }
662    Node::call("F", fa)
663}
664
665fn node_field(n: &Node) -> Option<Field> {
666    let Node::Call(fh, fa) = n else {
667        return None;
668    };
669    if fh != "F" || fa.len() < 2 {
670        return None;
671    }
672    let string = |n: &Node| match n {
673        Node::Str(s) => Some(s.clone()),
674        Node::Call(..) => None,
675    };
676    // #2689: a trailing `D()` marks a defaulted field; the rest are predicates.
677    let (defaulted, preds) = match fa.last() {
678        Some(Node::Call(h, a)) if fa.len() > 2 && h == "D" && a.is_empty() => {
679            (true, &fa[2..fa.len() - 1])
680        }
681        _ => (false, &fa[2..]),
682    };
683    Some(Field {
684        name: string(&fa[0])?,
685        ty: node_shape(&fa[1])?,
686        preds: preds.iter().map(string).collect::<Option<_>>()?,
687        defaulted,
688    })
689}
690
691fn shape_node(s: &Shape) -> Node {
692    let one = |h: &str, a: &Shape| Node::call(h, vec![shape_node(a)]);
693    match s {
694        Shape::Base(b) => Node::call("B", vec![Node::Str(b.clone())]),
695        Shape::Unit => Node::call("U", vec![]),
696        Shape::List(a) => one("L", a),
697        Shape::Set(a) => one("St", a),
698        Shape::Option(a) => one("O", a),
699        Shape::HttpResult(a) => one("H", a),
700        Shape::Result(a, b) => Node::call("R", vec![shape_node(a), shape_node(b)]),
701        Shape::Map(k, v) => Node::call("M", vec![shape_node(k), shape_node(v)]),
702        Shape::Named(n) => Node::call("N", vec![Node::Str(n.clone())]),
703        Shape::Ref(n) => Node::call("Ref", vec![Node::Str(n.clone())]),
704        Shape::Record { name, fields } => {
705            let mut args = vec![Node::Str(name.clone())];
706            args.extend(fields.iter().map(field_node));
707            Node::call("Rec", args)
708        }
709        Shape::Sum { name, variants } => {
710            let mut args = vec![Node::Str(name.clone())];
711            for v in variants {
712                let mut va = vec![Node::Str(v.name.clone())];
713                va.extend(v.payload.iter().map(field_node));
714                args.push(Node::call("V", va));
715            }
716            Node::call("Sum", args)
717        }
718        Shape::Refined { name, base, preds } => {
719            let mut args = vec![Node::Str(name.clone()), Node::Str(base.clone())];
720            args.extend(strs(preds));
721            Node::call("Rf", args)
722        }
723        Shape::Opaque { name, base } => {
724            Node::call("Op", vec![Node::Str(name.clone()), Node::Str(base.clone())])
725        }
726        Shape::App { head, args } => {
727            let mut a = vec![shape_node(head)];
728            a.extend(args.iter().map(shape_node));
729            Node::call("A", a)
730        }
731    }
732}
733
734fn node_shape(n: &Node) -> Option<Shape> {
735    let Node::Call(head, args) = n else {
736        return None;
737    };
738    let string = |n: &Node| match n {
739        Node::Str(s) => Some(s.clone()),
740        Node::Call(..) => None,
741    };
742    let sub = |i: usize| node_shape(args.get(i)?).map(Box::new);
743    let arity = |k: usize| (args.len() == k).then_some(());
744    Some(match head.as_str() {
745        "B" => {
746            arity(1)?;
747            Shape::Base(string(&args[0])?)
748        }
749        "U" => {
750            arity(0)?;
751            Shape::Unit
752        }
753        "L" => {
754            arity(1)?;
755            Shape::List(sub(0)?)
756        }
757        "O" => {
758            arity(1)?;
759            Shape::Option(sub(0)?)
760        }
761        "H" => {
762            arity(1)?;
763            Shape::HttpResult(sub(0)?)
764        }
765        "R" => {
766            arity(2)?;
767            Shape::Result(sub(0)?, sub(1)?)
768        }
769        "M" => {
770            arity(2)?;
771            Shape::Map(sub(0)?, sub(1)?)
772        }
773        "N" => {
774            arity(1)?;
775            Shape::Named(string(&args[0])?)
776        }
777        "Ref" => {
778            arity(1)?;
779            Shape::Ref(string(&args[0])?)
780        }
781        "Rec" => {
782            let name = string(args.first()?)?;
783            let fields = args[1..].iter().map(node_field).collect::<Option<_>>()?;
784            Shape::Record { name, fields }
785        }
786        "Sum" => {
787            let name = string(args.first()?)?;
788            let mut variants = Vec::new();
789            for v in &args[1..] {
790                let Node::Call(vh, va) = v else {
791                    return None;
792                };
793                if vh != "V" || va.is_empty() {
794                    return None;
795                }
796                variants.push(Variant {
797                    name: string(&va[0])?,
798                    payload: va[1..].iter().map(node_field).collect::<Option<_>>()?,
799                });
800            }
801            Shape::Sum { name, variants }
802        }
803        "Rf" => {
804            if args.len() < 2 {
805                return None;
806            }
807            Shape::Refined {
808                name: string(&args[0])?,
809                base: string(&args[1])?,
810                preds: args[2..].iter().map(string).collect::<Option<_>>()?,
811            }
812        }
813        "Op" => {
814            arity(2)?;
815            Shape::Opaque {
816                name: string(&args[0])?,
817                base: string(&args[1])?,
818            }
819        }
820        "A" => {
821            if args.is_empty() {
822                return None;
823            }
824            Shape::App {
825                head: sub(0)?,
826                args: args[1..].iter().map(node_shape).collect::<Option<_>>()?,
827            }
828        }
829        _ => return None,
830    })
831}
832
833// ---- the classifier -------------------------------------------------------------
834
835/// Which half of the call a finding is about.
836#[derive(Debug, Clone, Copy, PartialEq, Eq)]
837pub enum Direction {
838    /// Arguments, caller to callee.
839    Request,
840    /// The result, callee to caller.
841    Response,
842}
843
844impl Direction {
845    pub fn name(self) -> &'static str {
846        match self {
847            Direction::Request => "request",
848            Direction::Response => "response",
849        }
850    }
851}
852
853/// One difference between the two contracts, and whether the call survives it.
854#[derive(Debug, Clone, PartialEq, Eq)]
855pub struct Finding {
856    pub direction: Direction,
857    /// Where in the request or response: `request.order.qty`, `response`.
858    pub path: String,
859    pub breaking: bool,
860    pub message: String,
861}
862
863#[derive(Debug, Clone, Copy, PartialEq, Eq)]
864pub enum Verdict {
865    /// The two contracts are the same.
866    Unchanged,
867    /// They differ, but the caller still works against the callee.
868    Compatible,
869    /// Some call the caller can make is refused, or some answer it cannot read.
870    Breaking,
871}
872
873impl Verdict {
874    pub fn name(self) -> &'static str {
875        match self {
876            Verdict::Unchanged => "unchanged",
877            Verdict::Compatible => "compatible",
878            Verdict::Breaking => "breaking",
879        }
880    }
881}
882
883#[derive(Debug, Clone, PartialEq, Eq)]
884pub struct Compatibility {
885    pub verdict: Verdict,
886    pub findings: Vec<Finding>,
887}
888
889impl Compatibility {
890    /// One line per finding, breaking ones first, for a terminal or a panel:
891    /// `breaking request.note: the callee requires …`.
892    pub fn lines(&self) -> Vec<String> {
893        let mut findings: Vec<&Finding> = self.findings.iter().collect();
894        findings.sort_by_key(|f| !f.breaking);
895        findings
896            .into_iter()
897            .map(|f| {
898                format!(
899                    "{} {}: {}",
900                    if f.breaking { "breaking" } else { "compatible" },
901                    f.path,
902                    f.message
903                )
904            })
905            .collect()
906    }
907
908    /// The findings that make the verdict `Breaking`.
909    pub fn breaking(&self) -> impl Iterator<Item = &Finding> {
910        self.findings.iter().filter(|f| f.breaking)
911    }
912}
913
914/// Can a caller compiled against `caller` safely call a callee providing
915/// `callee`?
916///
917/// Both deploy skews are this one question. Pushing a callee over live callers
918/// asks it of `(what the callers recorded, what the new build provides)`;
919/// pushing a caller over a live callee asks it of `(what the new build expects,
920/// what the callee records)`. The editor's "old contract to new contract" is
921/// the first.
922pub fn check_call(caller: &ServiceShape, callee: &ServiceShape) -> Compatibility {
923    let mut cx = Cx::default();
924    if caller == callee {
925        return Compatibility {
926            verdict: Verdict::Unchanged,
927            findings: Vec::new(),
928        };
929    }
930    if caller.name != callee.name {
931        cx.push(
932            Direction::Request,
933            &caller.name,
934            true,
935            format!("the service is `{}`, not `{}`", callee.name, caller.name),
936        );
937    }
938    cx.dir = Direction::Request;
939    cx.params(&caller.params, &callee.params);
940    cx.dir = Direction::Response;
941    cx.flows(&callee.ret, &[], &caller.ret, &[], "response");
942    let breaking = cx.findings.iter().any(|f| f.breaking);
943    Compatibility {
944        verdict: if breaking {
945            Verdict::Breaking
946        } else {
947            Verdict::Compatible
948        },
949        findings: cx.findings,
950    }
951}
952
953struct Cx {
954    dir: Direction,
955    findings: Vec<Finding>,
956}
957
958impl Default for Cx {
959    fn default() -> Self {
960        Cx {
961            dir: Direction::Request,
962            findings: Vec::new(),
963        }
964    }
965}
966
967impl Cx {
968    fn push(&mut self, direction: Direction, path: &str, breaking: bool, message: String) {
969        self.findings.push(Finding {
970            direction,
971            path: path.to_string(),
972            breaking,
973            message,
974        });
975    }
976
977    fn note(&mut self, path: &str, breaking: bool, message: String) {
978        let dir = self.dir;
979        self.push(dir, path, breaking, message);
980    }
981
982    /// Who sends and who receives, in the words of a finding.
983    fn roles(&self) -> (&'static str, &'static str) {
984        match self.dir {
985            Direction::Request => ("caller", "callee"),
986            Direction::Response => ("callee", "caller"),
987        }
988    }
989
990    /// The parameter list is the request body: one parameter travels bare, two
991    /// or more as an object keyed by parameter name.
992    fn params(&mut self, caller: &[(String, Shape)], callee: &[(String, Shape)]) {
993        match (caller, callee) {
994            ([], []) => {}
995            ([(cn, c)], [(en, e)]) => {
996                let path = "request".to_string();
997                if cn != en {
998                    self.note(
999                        &path,
1000                        false,
1001                        format!("the parameter is renamed `{cn}` to `{en}`; one parameter travels as a bare value, so the name is not on the wire"),
1002                    );
1003                }
1004                self.flows(c, &[], e, &[], &path);
1005            }
1006            (c, e) if c.len() >= 2 && e.len() >= 2 => {
1007                for (en, eshape) in e {
1008                    let path = format!("request.{en}");
1009                    match c.iter().find(|(cn, _)| cn == en) {
1010                        Some((_, cshape)) => self.flows(cshape, &[], eshape, &[], &path),
1011                        None if matches!(eshape, Shape::Option(_)) => self.note(
1012                            &path,
1013                            false,
1014                            format!("the callee adds the optional parameter `{en}`; callers that omit it send `None`"),
1015                        ),
1016                        None => self.note(
1017                            &path,
1018                            true,
1019                            format!("the callee requires the parameter `{en}`, which the caller does not send"),
1020                        ),
1021                    }
1022                }
1023                for (cn, _) in c {
1024                    if !e.iter().any(|(en, _)| en == cn) {
1025                        self.note(
1026                            &format!("request.{cn}"),
1027                            false,
1028                            format!("the callee drops the parameter `{cn}`; unknown keys are ignored"),
1029                        );
1030                    }
1031                }
1032            }
1033            (c, e) => self.note(
1034                "request",
1035                true,
1036                format!(
1037                    "the parameter list changes shape ({} to {} parameters); one parameter is sent bare and several as an object",
1038                    c.len(),
1039                    e.len()
1040                ),
1041            ),
1042        }
1043    }
1044
1045    /// Can the receiver decode every value of `sender`? `sp`/`rp` are inline
1046    /// field refinements that sit beside the type.
1047    fn flows(&mut self, s: &Shape, sp: &[String], r: &Shape, rp: &[String], path: &str) {
1048        let (sender, receiver) = self.roles();
1049        // A generic instantiation is its expanded head; the arguments are
1050        // already substituted into it.
1051        if let Shape::App { head, .. } = s {
1052            return self.flows(head, sp, r, rp, path);
1053        }
1054        if let Shape::App { head, .. } = r {
1055            return self.flows(s, sp, head, rp, path);
1056        }
1057        // A bare value is accepted where an `Option` is expected.
1058        if let (false, Shape::Option(ri)) = (matches!(s, Shape::Option(_)), r) {
1059            self.note(
1060                path,
1061                false,
1062                format!("made optional: the {receiver} accepts a bare value as `Some`"),
1063            );
1064            return self.flows(s, sp, ri, rp, path);
1065        }
1066        if let (Some((sb, sset)), Some((rb, rset))) = (leaf(s, sp), leaf(r, rp)) {
1067            if sb != rb {
1068                return self.note(
1069                    path,
1070                    true,
1071                    format!("the type changes from `{sb}` to `{rb}`"),
1072                );
1073            }
1074            return self.refinements(&sb, &sset, &rset, path);
1075        }
1076        match (s, r) {
1077            (Shape::Unit, Shape::Unit) => {}
1078            (Shape::Named(a), Shape::Named(b)) if a == b => {}
1079            (Shape::Ref(a), Shape::Ref(b)) if a == b => {}
1080            (Shape::Opaque { base: a, .. }, Shape::Opaque { base: b, .. }) if a == b => {}
1081            (Shape::List(a), Shape::List(b)) => self.flows(a, &[], b, &[], &format!("{path}[]")),
1082            (Shape::HttpResult(a), Shape::HttpResult(b)) => {
1083                self.flows(a, &[], b, &[], &format!("{path}.value"))
1084            }
1085            (Shape::Option(a), Shape::Option(b)) => self.flows(a, &[], b, &[], &format!("{path}?")),
1086            (Shape::Result(ao, ae), Shape::Result(bo, be)) => {
1087                self.flows(ao, &[], bo, &[], &format!("{path}.ok"));
1088                self.flows(ae, &[], be, &[], &format!("{path}.err"));
1089            }
1090            (Shape::Map(ak, av), Shape::Map(bk, bv)) => {
1091                self.flows(ak, &[], bk, &[], &format!("{path}.key"));
1092                self.flows(av, &[], bv, &[], &format!("{path}[]"));
1093            }
1094            (Shape::Record { fields: sf, .. }, Shape::Record { fields: rf, .. }) => {
1095                for rfield in rf {
1096                    let fpath = format!("{path}.{}", rfield.name);
1097                    match sf.iter().find(|f| f.name == rfield.name) {
1098                        Some(sfield) => {
1099                            self.flows(&sfield.ty, &sfield.preds, &rfield.ty, &rfield.preds, &fpath)
1100                        }
1101                        None if rfield.defaulted && !matches!(rfield.ty, Shape::Option(_)) => {
1102                            self.note(
1103                                &fpath,
1104                                false,
1105                                format!("the {receiver} fills the field `{}`, which the {sender} does not send, with its default", rfield.name),
1106                            )
1107                        }
1108                        None if matches!(rfield.ty, Shape::Option(_)) => self.note(
1109                            &fpath,
1110                            false,
1111                            format!("the {sender} no longer sends the optional field `{}`; the {receiver} reads `None`", rfield.name),
1112                        ),
1113                        None => self.note(
1114                            &fpath,
1115                            true,
1116                            format!("the {receiver} requires the field `{}`, which the {sender} does not send{}", rfield.name, DEFAULT_HINT),
1117                        ),
1118                    }
1119                }
1120                for sfield in sf {
1121                    if !rf.iter().any(|f| f.name == sfield.name) {
1122                        self.note(
1123                            &format!("{path}.{}", sfield.name),
1124                            false,
1125                            format!(
1126                                "the {sender} sends the field `{}`, which the {receiver} ignores",
1127                                sfield.name
1128                            ),
1129                        );
1130                    }
1131                }
1132            }
1133            (Shape::Sum { variants: sv, .. }, Shape::Sum { variants: rv, .. }) => {
1134                for svar in sv {
1135                    let vpath = format!("{path}.{}", svar.name);
1136                    match rv.iter().find(|v| v.name == svar.name) {
1137                        None => self.note(
1138                            &vpath,
1139                            true,
1140                            format!("the {sender} can send the variant `{}`, which the {receiver} does not handle", svar.name),
1141                        ),
1142                        Some(rvar) => {
1143                            // Payload fields are keyed by name on the wire, so
1144                            // the classifier errs towards breaking on any
1145                            // difference in the set of names.
1146                            if payload_names(svar) != payload_names(rvar) {
1147                                self.note(
1148                                    &vpath,
1149                                    true,
1150                                    format!(
1151                                        "the payload fields of the variant `{}` change from ({}) to ({}); payload fields are keyed by name",
1152                                        svar.name,
1153                                        payload_names(svar).join(", "),
1154                                        payload_names(rvar).join(", ")
1155                                    ),
1156                                );
1157                            } else {
1158                                for sf in &svar.payload {
1159                                    if let Some(rf) = rvar.payload.iter().find(|f| f.name == sf.name) {
1160                                        self.flows(&sf.ty, &[], &rf.ty, &[], &format!("{vpath}.{}", sf.name));
1161                                    }
1162                                }
1163                            }
1164                        }
1165                    }
1166                }
1167                for rvar in rv {
1168                    if !sv.iter().any(|v| v.name == rvar.name) {
1169                        self.note(
1170                            &format!("{path}.{}", rvar.name),
1171                            false,
1172                            format!("the {receiver} also handles the variant `{}`, which the {sender} never sends", rvar.name),
1173                        );
1174                    }
1175                }
1176            }
1177            (a, b) => self.note(
1178                path,
1179                true,
1180                format!("the type changes from `{}` to `{}`", render(a), render(b)),
1181            ),
1182        }
1183    }
1184
1185    /// A numeric or string base on both sides: the receiver's predicates must
1186    /// each follow from the sender's.
1187    fn refinements(&mut self, base: &str, sender: &[String], receiver: &[String], path: &str) {
1188        if sender == receiver {
1189            return;
1190        }
1191        let (s, r) = self.roles();
1192        let unmet = unmet(base, sender, receiver);
1193        if unmet.is_empty() {
1194            self.note(
1195                path,
1196                false,
1197                format!(
1198                    "the refinement changes, and the {r} still accepts everything the {s} sends"
1199                ),
1200            );
1201        } else {
1202            let list: Vec<&str> = unmet.iter().map(|q| q.as_str()).collect();
1203            self.note(
1204                path,
1205                true,
1206                format!(
1207                    "the {r} requires {}, which the {s} does not guarantee",
1208                    list.join(", ")
1209                ),
1210            );
1211        }
1212    }
1213}
1214
1215/// A variant's payload field names, sorted.
1216fn payload_names(v: &Variant) -> Vec<&str> {
1217    let mut n: Vec<&str> = v.payload.iter().map(|f| f.name.as_str()).collect();
1218    n.sort_unstable();
1219    n
1220}
1221
1222/// Appended to a missing-field finding: a default is not hashed, but the
1223/// stored shape marks which fields have one (#2689), so only an `Option` or a
1224/// defaulted field may be absent.
1225const DEFAULT_HINT: &str = " (only an `Option` or a field with a default may be absent)";
1226
1227/// A base type with its predicates, whether it is written as a base, an inline
1228/// refinement on a base, or a named refined type. `None` for anything with
1229/// structure.
1230fn leaf(s: &Shape, field_preds: &[String]) -> Option<(String, Vec<String>)> {
1231    let (base, mut preds) = match s {
1232        Shape::Base(b) => (b.clone(), Vec::new()),
1233        Shape::Refined { base, preds, .. } => (base.clone(), preds.clone()),
1234        _ => return None,
1235    };
1236    preds.extend(field_preds.iter().cloned());
1237    preds.sort();
1238    preds.dedup();
1239    Some((base, preds))
1240}
1241
1242#[cfg(test)]
1243mod tests {
1244    use super::*;
1245    use crate::contract::service_normal_form;
1246
1247    fn types_of(src: &str) -> HashMap<String, Arc<TypeDecl>> {
1248        let tokens = bynk_syntax::lexer::tokenize(src).expect("lex");
1249        let commons = bynk_syntax::parser::parse(&tokens, src).expect("parse");
1250        commons
1251            .items
1252            .iter()
1253            .filter_map(|i| match i {
1254                bynk_syntax::ast::CommonsItem::Type(t) => {
1255                    Some((t.name.name.clone(), Arc::new(t.clone())))
1256                }
1257                _ => None,
1258            })
1259            .collect()
1260    }
1261
1262    fn sp() -> bynk_syntax::span::Span {
1263        bynk_syntax::span::Span::new(0, 0)
1264    }
1265
1266    fn named(n: &str) -> TypeRef {
1267        TypeRef::Named(bynk_syntax::ast::Ident {
1268            name: n.to_string(),
1269            span: sp(),
1270        })
1271    }
1272
1273    fn service(params: Vec<(&str, TypeRef)>, ret: TypeRef) -> CrossContextService {
1274        CrossContextService {
1275            name: "probe".to_string(),
1276            params: params
1277                .into_iter()
1278                .map(|(n, t)| (n.to_string(), t))
1279                .collect(),
1280            return_type: ret,
1281            span: sp(),
1282            foreign_callers: Vec::new(),
1283        }
1284    }
1285
1286    /// `probe(req: Req) -> Resp` over the declarations in `src`.
1287    fn shape(src: &str) -> ServiceShape {
1288        let types = types_of(&format!("commons x\n\n{src}\n"));
1289        ServiceShape::of(&service(vec![("req", named("Req"))], named("Resp")), &types)
1290    }
1291
1292    fn verdict(old: &str, new: &str) -> Compatibility {
1293        // Old callers against the new callee.
1294        check_call(&shape(old), &shape(new))
1295    }
1296
1297    fn breaking(old: &str, new: &str) -> Compatibility {
1298        let c = verdict(old, new);
1299        assert_eq!(c.verdict, Verdict::Breaking, "{c:#?}");
1300        assert!(c.breaking().count() > 0);
1301        c
1302    }
1303
1304    fn compatible(old: &str, new: &str) -> Compatibility {
1305        let c = verdict(old, new);
1306        assert_eq!(c.verdict, Verdict::Compatible, "{c:#?}");
1307        assert!(!c.findings.is_empty(), "a change has a reason");
1308        c
1309    }
1310
1311    fn only(c: &Compatibility, dir: Direction, path: &str) {
1312        assert!(
1313            c.findings
1314                .iter()
1315                .any(|f| f.direction == dir && f.path == path),
1316            "no {dir:?} finding at `{path}`: {c:#?}"
1317        );
1318    }
1319
1320    const REQ: &str = "type Resp = { ok: Bool }\n";
1321    const RESP: &str = "type Req = { id: Int }\n";
1322
1323    // ---- the shape is the normal form ---------------------------------------
1324
1325    #[test]
1326    fn a_shape_renders_the_exact_normal_form_and_hash() {
1327        let types = types_of(
1328            "commons x\n\n\
1329             type Age = Int where InRange(0, 150)\n\
1330             type Tag = String where NonEmpty && MaxLength(8)\n\
1331             type Token = opaque String\n\
1332             type Shape = | Circle(radius: Float) | Rect(w: Float, h: Float) | Dot\n\
1333             type Node = { next: Option[Node], v: Int where Positive }\n\
1334             type Page[T] = { items: List[T], tag: Tag }\n\
1335             type Bag = { age: Age, shape: Shape, tok: Token, m: Map[String, Page[Age]], r: Result[Node, String], u: () }\n",
1336        );
1337        let svc = service(
1338            vec![("a", named("Bag")), ("b", TypeRef::Unit(sp()))],
1339            named("Node"),
1340        );
1341        let s = ServiceShape::of(&svc, &types);
1342        assert_eq!(s.normal_form(), service_normal_form(&svc, &types));
1343        assert_eq!(
1344            s.hash(),
1345            crate::contract::service_contract_hash(&svc, &types)
1346        );
1347    }
1348
1349    #[test]
1350    fn a_shape_round_trips_through_its_text() {
1351        let types = types_of(
1352            "commons x\n\n\
1353             type Age = Int where InRange(0, 150)\n\
1354             type Token = opaque String\n\
1355             type Shape = | Circle(radius: Float) | Dot\n\
1356             type Node = { next: Option[Node], v: Int where Positive }\n\
1357             type Page[T] = { items: List[T] }\n\
1358             type Bag = { age: Age, shape: Shape, tok: Token, p: Page[Age] }\n",
1359        );
1360        let svc = service(vec![("a", named("Bag"))], named("Node"));
1361        let s = ServiceShape::of(&svc, &types);
1362        let text = s.to_text();
1363        assert_eq!(ServiceShape::from_text(&text), Some(s.clone()), "{text}");
1364        assert_eq!(
1365            ServiceShape::from_text_checked(&text, &s.hash()),
1366            Some(s.clone())
1367        );
1368        assert_eq!(
1369            ServiceShape::from_text_checked(&text, "0000000000000000"),
1370            None,
1371            "a shape that does not hash to its recorded hash is not trusted"
1372        );
1373    }
1374
1375    #[test]
1376    fn text_that_is_not_a_shape_reads_as_none() {
1377        for bad in [
1378            "",
1379            "Svc(",
1380            "Svc(\"a\")",
1381            "X()",
1382            "Svc(\"a\",Ret(Q()))",
1383            "junk",
1384        ] {
1385            assert_eq!(ServiceShape::from_text(bad), None, "{bad:?}");
1386        }
1387    }
1388
1389    // ---- unchanged ------------------------------------------------------------
1390
1391    #[test]
1392    fn identical_contracts_are_unchanged() {
1393        let s = shape(&format!("{REQ}{RESP}"));
1394        let c = check_call(&s, &s);
1395        assert_eq!((c.verdict, c.findings.len()), (Verdict::Unchanged, 0));
1396    }
1397
1398    // ---- record fields: requests --------------------------------------------------
1399
1400    #[test]
1401    fn request_optional_field_added_is_compatible() {
1402        let c = compatible(
1403            &format!("{REQ}type Req = {{ id: Int }}\n"),
1404            &format!("{REQ}type Req = {{ id: Int, note: Option[String] }}\n"),
1405        );
1406        only(&c, Direction::Request, "request.note");
1407    }
1408
1409    #[test]
1410    fn request_defaulted_field_added_is_compatible() {
1411        let c = compatible(
1412            &format!("{REQ}type Req = {{ id: Int }}\n"),
1413            &format!("{REQ}type Req = {{ id: Int, currency: String = \"EUR\" }}\n"),
1414        );
1415        only(&c, Direction::Request, "request.currency");
1416    }
1417
1418    #[test]
1419    fn a_default_does_not_hide_a_retype_or_a_new_required_field() {
1420        breaking(
1421            &format!("{REQ}type Req = {{ id: Int, c: String = \"a\" }}\n"),
1422            &format!("{REQ}type Req = {{ id: Int, c: Int = 1 }}\n"),
1423        );
1424        breaking(
1425            &format!("{REQ}type Req = {{ id: Int }}\n"),
1426            &format!("{REQ}type Req = {{ id: Int, c: String = \"a\", d: Int }}\n"),
1427        );
1428    }
1429
1430    #[test]
1431    fn response_defaulted_field_removed_is_compatible_when_the_caller_expects_a_default() {
1432        compatible(
1433            &format!("{RESP}type Resp = {{ ok: Bool, at: Int = 0 }}\n"),
1434            &format!("{RESP}type Resp = {{ ok: Bool }}\n"),
1435        );
1436    }
1437
1438    #[test]
1439    fn a_default_is_in_the_text_but_not_in_the_normal_form_or_the_hash() {
1440        let with = shape(&format!(
1441            "{REQ}type Req = {{ id: Int, c: String = \"a\" }}\n"
1442        ));
1443        let without = shape(&format!("{REQ}type Req = {{ id: Int, c: String }}\n"));
1444        assert_eq!(with.normal_form(), without.normal_form());
1445        assert_eq!(with.hash(), without.hash());
1446        assert_ne!(with.to_text(), without.to_text());
1447        assert_eq!(
1448            ServiceShape::from_text(&with.to_text()).as_ref(),
1449            Some(&with)
1450        );
1451        assert_eq!(
1452            ServiceShape::from_text(&without.to_text()).as_ref(),
1453            Some(&without)
1454        );
1455    }
1456
1457    /// Shape text as a build wrote it before the `D()` marker existed (#2689),
1458    /// hard-coded: the response of a service whose `at` field the caller expects.
1459    const LEGACY_EXPECTS_AT: &str = r#"Svc("probe",P("req",Rec("Req",F("id",B("Int")))),Ret(Rec("Resp",F("at",B("Int")),F("ok",B("Bool")))))"#;
1460
1461    #[test]
1462    fn text_written_before_the_marker_reads_as_having_no_default() {
1463        let legacy = ServiceShape::from_text(LEGACY_EXPECTS_AT).expect("legacy text parses");
1464        let Shape::Record { fields, .. } = &legacy.ret else {
1465            panic!("a record response");
1466        };
1467        assert!(fields.iter().all(|f| !f.defaulted));
1468        // The current build writes the marker only where a default is declared.
1469        let current = shape("type Req = { id: Int }\ntype Resp = { ok: Bool, at: Int = 0 }\n");
1470        assert_eq!(
1471            current.to_text(),
1472            LEGACY_EXPECTS_AT.replace("B(\"Int\")),F(\"ok\"", "B(\"Int\"),D()),F(\"ok\"")
1473        );
1474    }
1475
1476    #[test]
1477    fn a_legacy_expectation_of_a_removed_field_is_still_breaking() {
1478        // The caller's recorded expectation predates the marker, so the field it
1479        // reads cannot be credited with a default: the response direction stays
1480        // breaking until the caller redeploys.
1481        let caller = ServiceShape::from_text(LEGACY_EXPECTS_AT).unwrap();
1482        let callee = shape("type Req = { id: Int }\ntype Resp = { ok: Bool }\n");
1483        assert_eq!(check_call(&caller, &callee).verdict, Verdict::Breaking);
1484        // The same expectation recorded by this build is compatible.
1485        let fresh = shape("type Req = { id: Int }\ntype Resp = { ok: Bool, at: Int = 0 }\n");
1486        assert_eq!(check_call(&fresh, &callee).verdict, Verdict::Compatible);
1487    }
1488
1489    #[test]
1490    fn request_required_field_added_is_breaking() {
1491        let c = breaking(
1492            &format!("{REQ}type Req = {{ id: Int }}\n"),
1493            &format!("{REQ}type Req = {{ id: Int, note: String }}\n"),
1494        );
1495        only(&c, Direction::Request, "request.note");
1496    }
1497
1498    #[test]
1499    fn request_field_removed_is_compatible_because_the_callee_ignores_it() {
1500        let c = compatible(
1501            &format!("{REQ}type Req = {{ id: Int, note: String }}\n"),
1502            &format!("{REQ}type Req = {{ id: Int }}\n"),
1503        );
1504        only(&c, Direction::Request, "request.note");
1505    }
1506
1507    #[test]
1508    fn request_field_made_optional_is_compatible() {
1509        compatible(
1510            &format!("{REQ}type Req = {{ id: Int, note: String }}\n"),
1511            &format!("{REQ}type Req = {{ id: Int, note: Option[String] }}\n"),
1512        );
1513    }
1514
1515    #[test]
1516    fn request_field_made_required_is_breaking() {
1517        let c = breaking(
1518            &format!("{REQ}type Req = {{ id: Int, note: Option[String] }}\n"),
1519            &format!("{REQ}type Req = {{ id: Int, note: String }}\n"),
1520        );
1521        only(&c, Direction::Request, "request.note");
1522    }
1523
1524    #[test]
1525    fn request_field_retyped_is_breaking() {
1526        breaking(
1527            &format!("{REQ}type Req = {{ id: Int }}\n"),
1528            &format!("{REQ}type Req = {{ id: String }}\n"),
1529        );
1530    }
1531
1532    // ---- record fields: responses -------------------------------------------------
1533
1534    #[test]
1535    fn response_field_added_is_compatible() {
1536        let c = compatible(
1537            &format!("{RESP}type Resp = {{ ok: Bool }}\n"),
1538            &format!("{RESP}type Resp = {{ ok: Bool, at: Int }}\n"),
1539        );
1540        only(&c, Direction::Response, "response.at");
1541    }
1542
1543    #[test]
1544    fn response_required_field_removed_is_breaking() {
1545        let c = breaking(
1546            &format!("{RESP}type Resp = {{ ok: Bool, at: Int }}\n"),
1547            &format!("{RESP}type Resp = {{ ok: Bool }}\n"),
1548        );
1549        only(&c, Direction::Response, "response.at");
1550    }
1551
1552    #[test]
1553    fn response_optional_field_removed_is_compatible() {
1554        compatible(
1555            &format!("{RESP}type Resp = {{ ok: Bool, at: Option[Int] }}\n"),
1556            &format!("{RESP}type Resp = {{ ok: Bool }}\n"),
1557        );
1558    }
1559
1560    #[test]
1561    fn response_field_made_optional_is_breaking() {
1562        let c = breaking(
1563            &format!("{RESP}type Resp = {{ ok: Bool, at: Int }}\n"),
1564            &format!("{RESP}type Resp = {{ ok: Bool, at: Option[Int] }}\n"),
1565        );
1566        only(&c, Direction::Response, "response.at");
1567    }
1568
1569    #[test]
1570    fn response_field_made_required_is_compatible() {
1571        compatible(
1572            &format!("{RESP}type Resp = {{ ok: Bool, at: Option[Int] }}\n"),
1573            &format!("{RESP}type Resp = {{ ok: Bool, at: Int }}\n"),
1574        );
1575    }
1576
1577    #[test]
1578    fn response_field_retyped_is_breaking() {
1579        breaking(
1580            &format!("{RESP}type Resp = {{ ok: Bool }}\n"),
1581            &format!("{RESP}type Resp = {{ ok: String }}\n"),
1582        );
1583    }
1584
1585    #[test]
1586    fn field_order_is_not_a_change() {
1587        let c = check_call(
1588            &shape(&format!("{RESP}type Resp = {{ a: Int, b: Int }}\n")),
1589            &shape(&format!("{RESP}type Resp = {{ b: Int, a: Int }}\n")),
1590        );
1591        assert_eq!(c.verdict, Verdict::Unchanged);
1592    }
1593
1594    // ---- refinements ----------------------------------------------------------------
1595
1596    #[test]
1597    fn request_refinement_widened_is_compatible() {
1598        let c = compatible(
1599            &format!("{REQ}type Req = {{ qty: Int where InRange(1, 10) }}\n"),
1600            &format!("{REQ}type Req = {{ qty: Int where InRange(0, 100) }}\n"),
1601        );
1602        only(&c, Direction::Request, "request.qty");
1603    }
1604
1605    #[test]
1606    fn request_refinement_narrowed_is_breaking() {
1607        let c = breaking(
1608            &format!("{REQ}type Req = {{ qty: Int where InRange(0, 100) }}\n"),
1609            &format!("{REQ}type Req = {{ qty: Int where InRange(1, 10) }}\n"),
1610        );
1611        only(&c, Direction::Request, "request.qty");
1612    }
1613
1614    #[test]
1615    fn request_refinement_added_is_breaking_and_removed_is_compatible() {
1616        breaking(
1617            &format!("{REQ}type Req = {{ qty: Int }}\n"),
1618            &format!("{REQ}type Req = {{ qty: Int where Positive }}\n"),
1619        );
1620        compatible(
1621            &format!("{REQ}type Req = {{ qty: Int where Positive }}\n"),
1622            &format!("{REQ}type Req = {{ qty: Int }}\n"),
1623        );
1624    }
1625
1626    #[test]
1627    fn response_refinement_narrowed_is_compatible_and_widened_is_breaking() {
1628        compatible(
1629            &format!("{RESP}type Resp = {{ qty: Int where InRange(0, 100) }}\n"),
1630            &format!("{RESP}type Resp = {{ qty: Int where InRange(1, 10) }}\n"),
1631        );
1632        let c = breaking(
1633            &format!("{RESP}type Resp = {{ qty: Int where InRange(1, 10) }}\n"),
1634            &format!("{RESP}type Resp = {{ qty: Int where InRange(0, 100) }}\n"),
1635        );
1636        only(&c, Direction::Response, "response.qty");
1637    }
1638
1639    #[test]
1640    fn named_refined_types_follow_the_same_rules() {
1641        compatible(
1642            &format!("{REQ}type Age = Int where InRange(18, 65)\ntype Req = {{ age: Age }}\n"),
1643            &format!("{REQ}type Age = Int where InRange(0, 150)\ntype Req = {{ age: Age }}\n"),
1644        );
1645        breaking(
1646            &format!("{REQ}type Age = Int where InRange(0, 150)\ntype Req = {{ age: Age }}\n"),
1647            &format!("{REQ}type Age = Int where InRange(18, 65)\ntype Req = {{ age: Age }}\n"),
1648        );
1649    }
1650
1651    #[test]
1652    fn length_and_sign_predicates_entail_each_other() {
1653        // `Positive` implies `NonNegative`; `Length(3)` implies both bounds.
1654        compatible(
1655            &format!("{RESP}type Resp = {{ n: Int where NonNegative }}\n"),
1656            &format!("{RESP}type Resp = {{ n: Int where Positive }}\n"),
1657        );
1658        compatible(
1659            &format!("{REQ}type Req = {{ s: String where Length(3) }}\n"),
1660            &format!("{REQ}type Req = {{ s: String where MinLength(1) && MaxLength(8) }}\n"),
1661        );
1662        breaking(
1663            &format!("{REQ}type Req = {{ s: String where MaxLength(8) }}\n"),
1664            &format!("{REQ}type Req = {{ s: String where Length(3) }}\n"),
1665        );
1666    }
1667
1668    #[test]
1669    fn decimal_ranges_compare_by_value() {
1670        // #2802: `Decimal` bounds are decided by the shared engine, by value.
1671        compatible(
1672            &format!("{REQ}type Req = {{ p: Decimal where InRange(1.00d, 5.00d) }}\n"),
1673            &format!("{REQ}type Req = {{ p: Decimal where InRange(0.0d, 10.0d) }}\n"),
1674        );
1675        breaking(
1676            &format!("{REQ}type Req = {{ p: Decimal where InRange(0.0d, 10.0d) }}\n"),
1677            &format!("{REQ}type Req = {{ p: Decimal where InRange(1.00d, 5.00d) }}\n"),
1678        );
1679        compatible(
1680            &format!("{RESP}type Resp = {{ p: Decimal where NonNegative }}\n"),
1681            &format!("{RESP}type Resp = {{ p: Decimal where Positive }}\n"),
1682        );
1683        breaking(
1684            &format!("{REQ}type Req = {{ p: Decimal where NonNegative }}\n"),
1685            &format!("{REQ}type Req = {{ p: Decimal where Positive }}\n"),
1686        );
1687    }
1688
1689    #[test]
1690    fn a_changed_pattern_is_breaking_both_ways() {
1691        breaking(
1692            &format!("{REQ}type Req = {{ s: String where Matches(\"[a-z]+\") }}\n"),
1693            &format!("{REQ}type Req = {{ s: String where Matches(\"[a-z0-9]+\") }}\n"),
1694        );
1695    }
1696
1697    #[test]
1698    fn float_ranges_compare_by_value() {
1699        compatible(
1700            &format!("{REQ}type Req = {{ r: Float where InRange(0.5, 1.5) }}\n"),
1701            &format!("{REQ}type Req = {{ r: Float where InRange(0.0, 2.0) }}\n"),
1702        );
1703        breaking(
1704            &format!("{REQ}type Req = {{ r: Float where NonNegative }}\n"),
1705            &format!("{REQ}type Req = {{ r: Float where Positive }}\n"),
1706        );
1707        compatible(
1708            &format!("{RESP}type Resp = {{ r: Float where NonNegative }}\n"),
1709            &format!("{RESP}type Resp = {{ r: Float where Positive }}\n"),
1710        );
1711    }
1712
1713    // ---- sum types --------------------------------------------------------------------
1714
1715    #[test]
1716    fn request_variant_added_is_compatible_and_removed_is_breaking() {
1717        let one = format!("{REQ}type Kind = | A | B\ntype Req = {{ k: Kind }}\n");
1718        let two = format!("{REQ}type Kind = | A | B | C\ntype Req = {{ k: Kind }}\n");
1719        let c = compatible(&one, &two);
1720        only(&c, Direction::Request, "request.k.C");
1721        let c = breaking(&two, &one);
1722        only(&c, Direction::Request, "request.k.C");
1723    }
1724
1725    #[test]
1726    fn response_variant_added_is_breaking_and_removed_is_compatible() {
1727        let one = format!("{RESP}type Kind = | A | B\ntype Resp = {{ k: Kind }}\n");
1728        let two = format!("{RESP}type Kind = | A | B | C\ntype Resp = {{ k: Kind }}\n");
1729        let c = breaking(&one, &two);
1730        only(&c, Direction::Response, "response.k.C");
1731        compatible(&two, &one);
1732    }
1733
1734    #[test]
1735    fn a_variant_payload_change_is_breaking() {
1736        breaking(
1737            &format!("{RESP}type Resp = | A(n: Int) | B\n"),
1738            &format!("{RESP}type Resp = | A(n: String) | B\n"),
1739        );
1740        breaking(
1741            &format!("{RESP}type Resp = | A(n: Int) | B\n"),
1742            &format!("{RESP}type Resp = | A(n: Int, m: Int) | B\n"),
1743        );
1744    }
1745
1746    #[test]
1747    fn a_variant_payload_field_is_keyed_by_name() {
1748        // A rename is a wire break in either direction; a reorder is invisible.
1749        let c = breaking(
1750            &format!("{RESP}type Resp = | A(x: Int) | B\n"),
1751            &format!("{RESP}type Resp = | A(y: Int) | B\n"),
1752        );
1753        only(&c, Direction::Response, "response.A");
1754        breaking(
1755            &format!("{REQ}type Req = | A(x: Int) | B\n"),
1756            &format!("{REQ}type Req = | A(y: Int) | B\n"),
1757        );
1758        // The same name with another type, or made optional, goes through the
1759        // ordinary `flows` rule.
1760        breaking(
1761            &format!("{RESP}type Resp = | A(x: Int) | B\n"),
1762            &format!("{RESP}type Resp = | A(x: String) | B\n"),
1763        );
1764        breaking(
1765            &format!("{RESP}type Resp = | A(x: Int) | B\n"),
1766            &format!("{RESP}type Resp = | A(x: Option[Int]) | B\n"),
1767        );
1768        let reordered = check_call(
1769            &shape(&format!("{RESP}type Resp = | A(x: Int, y: String) | B\n")),
1770            &shape(&format!("{RESP}type Resp = | A(y: String, x: Int) | B\n")),
1771        );
1772        assert_eq!(reordered.verdict, Verdict::Unchanged);
1773        let (a, b) = (
1774            shape(&format!("{RESP}type Resp = | A(x: Int) | B\n")),
1775            shape(&format!("{RESP}type Resp = | A(y: Int) | B\n")),
1776        );
1777        assert_ne!(a.normal_form(), b.normal_form());
1778        for s in [&a, &b] {
1779            assert_eq!(ServiceShape::from_text(&s.to_text()).as_ref(), Some(s));
1780        }
1781    }
1782
1783    // ---- containers and the response itself ----------------------------------------------
1784
1785    #[test]
1786    fn element_types_are_checked_through_containers() {
1787        let c = breaking(
1788            &format!("{RESP}type Resp = {{ xs: List[Int] }}\n"),
1789            &format!("{RESP}type Resp = {{ xs: List[String] }}\n"),
1790        );
1791        only(&c, Direction::Response, "response.xs[]");
1792        compatible(
1793            &format!("{RESP}type Row = {{ a: Int }}\ntype Resp = {{ xs: List[Row] }}\n"),
1794            &format!("{RESP}type Row = {{ a: Int, b: Int }}\ntype Resp = {{ xs: List[Row] }}\n"),
1795        );
1796    }
1797
1798    #[test]
1799    fn a_response_made_optional_is_breaking_and_a_bare_request_made_optional_is_compatible() {
1800        let types = types_of("commons x\n");
1801        let svc = |param: TypeRef, ret: TypeRef| {
1802            ServiceShape::of(&service(vec![("p", param)], ret), &types)
1803        };
1804        let int = || TypeRef::Base(bynk_syntax::ast::BaseType::Int, sp());
1805        let opt = || TypeRef::Option(Box::new(int()), sp());
1806        let bare = svc(int(), int());
1807        let optional_param = svc(opt(), int());
1808        let optional_ret = svc(int(), opt());
1809        assert_eq!(
1810            check_call(&bare, &optional_param).verdict,
1811            Verdict::Compatible
1812        );
1813        assert_eq!(
1814            check_call(&optional_param, &bare).verdict,
1815            Verdict::Breaking
1816        );
1817        assert_eq!(check_call(&bare, &optional_ret).verdict, Verdict::Breaking);
1818        assert_eq!(
1819            check_call(&optional_ret, &bare).verdict,
1820            Verdict::Compatible
1821        );
1822    }
1823
1824    #[test]
1825    fn a_recursive_type_closes_on_itself() {
1826        let a = format!("{REQ}type Req = {{ next: Option[Req], v: Int }}\n");
1827        let b = format!("{REQ}type Req = {{ next: Option[Req], v: Int, tag: Option[String] }}\n");
1828        compatible(&a, &b);
1829        breaking(&a, &b.replace("Option[String]", "String"));
1830    }
1831
1832    // ---- parameters ----------------------------------------------------------------------------
1833
1834    fn params(old: &[(&str, &str)], new: &[(&str, &str)]) -> Compatibility {
1835        let types = types_of("commons x\n");
1836        let make = |ps: &[(&str, &str)]| {
1837            let ps = ps
1838                .iter()
1839                .map(|(n, t)| {
1840                    let ty = match *t {
1841                        "Int" => TypeRef::Base(bynk_syntax::ast::BaseType::Int, sp()),
1842                        "String" => TypeRef::Base(bynk_syntax::ast::BaseType::String, sp()),
1843                        "Option[String]" => TypeRef::Option(
1844                            Box::new(TypeRef::Base(bynk_syntax::ast::BaseType::String, sp())),
1845                            sp(),
1846                        ),
1847                        other => panic!("{other}"),
1848                    };
1849                    (*n, ty)
1850                })
1851                .collect();
1852            ServiceShape::of(
1853                &service(ps, TypeRef::Base(bynk_syntax::ast::BaseType::Int, sp())),
1854                &types,
1855            )
1856        };
1857        check_call(&make(old), &make(new))
1858    }
1859
1860    #[test]
1861    fn parameters_follow_the_keyed_object_rules() {
1862        let c = params(
1863            &[("a", "Int"), ("b", "Int")],
1864            &[("a", "Int"), ("b", "Int"), ("c", "Option[String]")],
1865        );
1866        assert_eq!(c.verdict, Verdict::Compatible, "{c:#?}");
1867        let c = params(
1868            &[("a", "Int"), ("b", "Int")],
1869            &[("a", "Int"), ("b", "Int"), ("c", "String")],
1870        );
1871        assert_eq!(c.verdict, Verdict::Breaking, "{c:#?}");
1872        only(&c, Direction::Request, "request.c");
1873        let c = params(&[("a", "Int"), ("b", "Int")], &[("a", "Int")]);
1874        assert_eq!(
1875            c.verdict,
1876            Verdict::Breaking,
1877            "one parameter is sent bare: {c:#?}"
1878        );
1879        let c = params(
1880            &[("a", "Int"), ("b", "Int"), ("c", "Int")],
1881            &[("b", "Int"), ("a", "Int")],
1882        );
1883        assert_eq!(c.verdict, Verdict::Compatible, "{c:#?}");
1884        let c = params(
1885            &[("a", "Int"), ("b", "Int")],
1886            &[("a", "Int"), ("b", "String")],
1887        );
1888        assert_eq!(c.verdict, Verdict::Breaking, "{c:#?}");
1889    }
1890
1891    #[test]
1892    fn a_single_parameter_is_bare_so_its_name_is_not_a_break() {
1893        let c = params(&[("a", "Int")], &[("n", "Int")]);
1894        assert_eq!(c.verdict, Verdict::Compatible, "{c:#?}");
1895        let c = params(&[("a", "Int")], &[("a", "String")]);
1896        assert_eq!(c.verdict, Verdict::Breaking, "{c:#?}");
1897        let c = params(&[], &[("a", "Int")]);
1898        assert_eq!(c.verdict, Verdict::Breaking, "{c:#?}");
1899    }
1900
1901    #[test]
1902    fn a_different_service_is_breaking() {
1903        let a = shape(&format!("{REQ}{RESP}"));
1904        let mut b = a.clone();
1905        b.name = "other".into();
1906        assert_eq!(check_call(&a, &b).verdict, Verdict::Breaking);
1907    }
1908
1909    // ---- the classifier against a model of the decoder ---------------------
1910    //
1911    // `check_call` says a change is compatible. This holds it to that: for
1912    // every pair of shapes in a pool, if the verdict is not `Breaking`, every
1913    // value the sender can produce must decode at the receiver, under the
1914    // decode rules of `reference/wire-format.md`. The model below is written
1915    // from that reference, not from the classifier.
1916    //
1917    // The converse is not asserted: the classifier is allowed to be
1918    // conservative. A sum's payload fields are keyed by name on the wire, as a
1919    // record's are, and the model keys them by name on both sides.
1920
1921    #[derive(Clone, Debug, PartialEq)]
1922    enum J {
1923        Bool(bool),
1924        Int(i64),
1925        Float(f64),
1926        Str(String),
1927        Arr(Vec<J>),
1928        Obj(Vec<(String, J)>),
1929    }
1930
1931    fn obj(fields: Vec<(&str, J)>) -> J {
1932        J::Obj(
1933            fields
1934                .into_iter()
1935                .map(|(k, v)| (k.to_string(), v))
1936                .collect(),
1937        )
1938    }
1939
1940    fn get<'a>(fields: &'a [(String, J)], key: &str) -> Option<&'a J> {
1941        fields.iter().find(|(k, _)| k == key).map(|(_, v)| v)
1942    }
1943
1944    /// The predicate, from its canonical text, held to a value.
1945    fn holds(pred: &str, v: &J) -> bool {
1946        let int = |j: &J| match j {
1947            J::Int(i) => Some(*i as f64),
1948            J::Float(f) => Some(*f),
1949            _ => None,
1950        };
1951        let len = |j: &J| match j {
1952            J::Str(s) => Some(s.chars().count() as i64),
1953            _ => None,
1954        };
1955        let args = |name: &str| -> Vec<f64> {
1956            pred.strip_prefix(name)
1957                .and_then(|r| r.strip_prefix('('))
1958                .and_then(|r| r.strip_suffix(')'))
1959                .map(|r| r.split(", ").map(|n| n.parse().unwrap()).collect())
1960                .unwrap_or_default()
1961        };
1962        match pred {
1963            "Positive" => int(v).is_some_and(|n| n > 0.0),
1964            "NonNegative" => int(v).is_some_and(|n| n >= 0.0),
1965            p if p.starts_with("InRangeF(") => {
1966                let a = args("InRangeF");
1967                int(v).is_some_and(|n| a[0] <= n && n <= a[1])
1968            }
1969            p if p.starts_with("InRange(") => {
1970                let a = args("InRange");
1971                int(v).is_some_and(|n| a[0] <= n && n <= a[1])
1972            }
1973            p if p.starts_with("MinLength(") => {
1974                len(v).is_some_and(|n| n as f64 >= args("MinLength")[0])
1975            }
1976            p if p.starts_with("MaxLength(") => {
1977                len(v).is_some_and(|n| n as f64 <= args("MaxLength")[0])
1978            }
1979            p if p.starts_with("Length(") => len(v).is_some_and(|n| n as f64 == args("Length")[0]),
1980            "IsoDate" => matches!(v, J::Str(s) if bynk_syntax::ast::is_iso_date(s)),
1981            "Cron" => matches!(v, J::Str(s) if bynk_syntax::cron::is_cron_expression(s).is_ok()),
1982            other => panic!("the model does not know {other}"),
1983        }
1984    }
1985
1986    /// Can `shape` (with the field's own `preds`) decode `v`?
1987    fn decodes(shape: &Shape, preds: &[String], v: &J) -> bool {
1988        let base = |b: &str, v: &J| {
1989            matches!(
1990                (b, v),
1991                ("Int", J::Int(_))
1992                    | ("String", J::Str(_))
1993                    | ("Bool", J::Bool(_))
1994                    | ("Float", J::Int(_) | J::Float(_))
1995            )
1996        };
1997        let checked =
1998            |b: &str, ps: &[String]| base(b, v) && ps.iter().chain(preds).all(|p| holds(p, v));
1999        match shape {
2000            Shape::Base(b) => checked(b, &[]),
2001            Shape::Refined {
2002                base: b, preds: ps, ..
2003            } => checked(b, ps),
2004            Shape::Option(inner) => match v {
2005                J::Obj(f) if get(f, "kind") == Some(&J::Str("None".into())) => true,
2006                J::Obj(f) if get(f, "kind") == Some(&J::Str("Some".into())) => {
2007                    get(f, "value").is_some_and(|x| decodes(inner, &[], x))
2008                }
2009                // A bare value is `Some`.
2010                other => decodes(inner, &[], other),
2011            },
2012            Shape::List(inner) => {
2013                matches!(v, J::Arr(xs) if xs.iter().all(|x| decodes(inner, &[], x)))
2014            }
2015            Shape::Map(k, val) => matches!(v, J::Arr(xs) if xs.iter().all(|pair| matches!(
2016                pair, J::Arr(kv) if kv.len() == 2 && decodes(k, &[], &kv[0]) && decodes(val, &[], &kv[1])
2017            ))),
2018            Shape::Result(ok, err) => match v {
2019                J::Obj(f) => match get(f, "kind") {
2020                    Some(J::Str(k)) if k == "Ok" => {
2021                        get(f, "value").is_some_and(|x| decodes(ok, &[], x))
2022                    }
2023                    Some(J::Str(k)) if k == "Err" => {
2024                        get(f, "error").is_some_and(|x| decodes(err, &[], x))
2025                    }
2026                    _ => false,
2027                },
2028                _ => false,
2029            },
2030            Shape::Record { fields, .. } => match v {
2031                J::Obj(given) => fields.iter().all(|f| match get(given, &f.name) {
2032                    Some(x) => decodes(&f.ty, &f.preds, x),
2033                    None => matches!(f.ty, Shape::Option(_)) || f.defaulted,
2034                }),
2035                _ => false,
2036            },
2037            Shape::Sum { variants, .. } => match v {
2038                J::Obj(given) => match get(given, "kind") {
2039                    Some(J::Str(k)) => variants.iter().find(|x| &x.name == k).is_some_and(|var| {
2040                        var.payload
2041                            .iter()
2042                            .all(|p| get(given, &p.name).is_some_and(|x| decodes(&p.ty, &[], x)))
2043                    }),
2044                    _ => false,
2045                },
2046                _ => false,
2047            },
2048            other => panic!("the model does not cover {other:?}"),
2049        }
2050    }
2051
2052    /// A small, fixed sample of what a sender of `shape` can produce.
2053    fn values(shape: &Shape, preds: &[String]) -> Vec<J> {
2054        let cap = |mut v: Vec<J>| {
2055            while v.len() > 40 {
2056                v.remove(v.len() / 2);
2057            }
2058            v
2059        };
2060        let keep = |vs: Vec<J>| -> Vec<J> {
2061            vs.into_iter()
2062                .filter(|v| preds.iter().all(|p| holds(p, v)))
2063                .collect()
2064        };
2065        match shape {
2066            Shape::Base(b) => keep(match b.as_str() {
2067                "Int" => [-1, 0, 1, 5, 200].map(J::Int).to_vec(),
2068                "Float" => [0.0, 0.5, 1.5].map(J::Float).to_vec(),
2069                "String" => ["", "a", "abc", "abcdefghij"]
2070                    .map(|s| J::Str(s.into()))
2071                    .to_vec(),
2072                "Bool" => vec![J::Bool(true), J::Bool(false)],
2073                other => panic!("{other}"),
2074            }),
2075            Shape::Refined {
2076                base, preds: ps, ..
2077            } => {
2078                let all: Vec<String> = ps.iter().chain(preds).cloned().collect();
2079                values(&Shape::Base(base.clone()), &all)
2080            }
2081            Shape::Option(inner) => {
2082                let mut out = vec![obj(vec![("kind", J::Str("None".into()))])];
2083                for v in values(inner, &[]).into_iter().take(3) {
2084                    out.push(obj(vec![("kind", J::Str("Some".into())), ("value", v)]));
2085                }
2086                out
2087            }
2088            Shape::List(inner) => {
2089                let vs = values(inner, &[]);
2090                let mut out = vec![J::Arr(vec![])];
2091                out.extend(vs.iter().take(2).map(|v| J::Arr(vec![v.clone()])));
2092                out.push(J::Arr(vs.into_iter().take(2).collect()));
2093                out
2094            }
2095            Shape::Map(k, v) => {
2096                let (ks, vs) = (values(k, &[]), values(v, &[]));
2097                vec![
2098                    J::Arr(vec![]),
2099                    J::Arr(vec![J::Arr(vec![ks[0].clone(), vs[0].clone()])]),
2100                ]
2101            }
2102            Shape::Result(ok, err) => {
2103                let mut out = Vec::new();
2104                for v in values(ok, &[]).into_iter().take(3) {
2105                    out.push(obj(vec![("kind", J::Str("Ok".into())), ("value", v)]));
2106                }
2107                for v in values(err, &[]).into_iter().take(3) {
2108                    out.push(obj(vec![("kind", J::Str("Err".into())), ("error", v)]));
2109                }
2110                out
2111            }
2112            Shape::Record { fields, .. } => {
2113                // Each field takes each of a few values, and an `Option` field
2114                // may also be left out.
2115                let mut rows: Vec<Vec<(String, J)>> = vec![vec![]];
2116                for f in fields {
2117                    let mut vs: Vec<Option<J>> = values(&f.ty, &f.preds)
2118                        .into_iter()
2119                        .take(3)
2120                        .map(Some)
2121                        .collect();
2122                    if matches!(f.ty, Shape::Option(_)) {
2123                        vs.push(None);
2124                    }
2125                    rows = rows
2126                        .into_iter()
2127                        .flat_map(|row| {
2128                            vs.iter().map(move |v| {
2129                                let mut r = row.clone();
2130                                if let Some(v) = v {
2131                                    r.push((f.name.clone(), v.clone()));
2132                                }
2133                                r
2134                            })
2135                        })
2136                        .collect();
2137                }
2138                cap(rows.into_iter().map(J::Obj).collect())
2139            }
2140            Shape::Sum { variants, .. } => {
2141                let mut out = Vec::new();
2142                for var in variants {
2143                    let mut rows: Vec<Vec<(String, J)>> =
2144                        vec![vec![("kind".into(), J::Str(var.name.clone()))]];
2145                    for p in &var.payload {
2146                        let vs: Vec<J> = values(&p.ty, &[]).into_iter().take(2).collect();
2147                        rows = rows
2148                            .into_iter()
2149                            .flat_map(|row| {
2150                                vs.iter().map(move |v| {
2151                                    let mut r = row.clone();
2152                                    r.push((p.name.clone(), v.clone()));
2153                                    r
2154                                })
2155                            })
2156                            .collect();
2157                    }
2158                    out.extend(rows.into_iter().map(J::Obj));
2159                }
2160                out
2161            }
2162            other => panic!("{other:?}"),
2163        }
2164    }
2165
2166    fn int() -> Shape {
2167        Shape::Base("Int".into())
2168    }
2169    fn string() -> Shape {
2170        Shape::Base("String".into())
2171    }
2172    fn refined(base: &str, preds: &[&str]) -> Shape {
2173        Shape::Refined {
2174            name: "T".into(),
2175            base: base.into(),
2176            preds: preds.iter().map(|p| p.to_string()).collect(),
2177        }
2178    }
2179    fn record(fields: Vec<(&str, Shape)>) -> Shape {
2180        Shape::Record {
2181            name: "R".into(),
2182            fields: fields
2183                .into_iter()
2184                .map(|(n, ty)| Field {
2185                    name: n.into(),
2186                    ty,
2187                    preds: Vec::new(),
2188                    defaulted: false,
2189                })
2190                .collect(),
2191        }
2192    }
2193    /// A record whose fields named in `defaulted` declare a default.
2194    fn drecord(fields: Vec<(&str, Shape)>, defaulted: &[&str]) -> Shape {
2195        let Shape::Record { name, mut fields } = record(fields) else {
2196            unreachable!()
2197        };
2198        for f in &mut fields {
2199            f.defaulted = defaulted.contains(&f.name.as_str());
2200        }
2201        Shape::Record { name, fields }
2202    }
2203    fn sum(variants: Vec<(&str, Vec<(&str, Shape)>)>) -> Shape {
2204        Shape::Sum {
2205            name: "S".into(),
2206            variants: variants
2207                .into_iter()
2208                .map(|(n, payload)| Variant {
2209                    name: n.into(),
2210                    payload: payload
2211                        .into_iter()
2212                        .map(|(f, ty)| Field {
2213                            name: f.into(),
2214                            ty,
2215                            preds: Vec::new(),
2216                            defaulted: false,
2217                        })
2218                        .collect(),
2219                })
2220                .collect(),
2221        }
2222    }
2223    fn opt(s: Shape) -> Shape {
2224        Shape::Option(Box::new(s))
2225    }
2226
2227    fn pool() -> Vec<Shape> {
2228        vec![
2229            int(),
2230            string(),
2231            Shape::Base("Bool".into()),
2232            Shape::Base("Float".into()),
2233            refined("Int", &["Positive"]),
2234            refined("Int", &["NonNegative"]),
2235            refined("Int", &["InRange(0, 10)"]),
2236            refined("Int", &["InRange(1, 5)"]),
2237            refined("Int", &["InRange(1, 5)", "Positive"]),
2238            refined("Float", &["Positive"]),
2239            refined("Float", &["InRangeF(0, 2)"]),
2240            refined("String", &["MinLength(1)"]),
2241            refined("String", &["MaxLength(5)"]),
2242            refined("String", &["Length(3)"]),
2243            refined("String", &["MinLength(1)", "MaxLength(5)"]),
2244            opt(int()),
2245            opt(string()),
2246            opt(refined("Int", &["Positive"])),
2247            Shape::List(Box::new(int())),
2248            Shape::List(Box::new(opt(int()))),
2249            Shape::Map(Box::new(string()), Box::new(int())),
2250            Shape::Result(Box::new(int()), Box::new(string())),
2251            Shape::Result(Box::new(int()), Box::new(int())),
2252            record(vec![]),
2253            record(vec![("a", int())]),
2254            record(vec![("b", int())]),
2255            record(vec![("a", opt(int()))]),
2256            record(vec![("a", int()), ("b", opt(int()))]),
2257            record(vec![("a", int()), ("b", int())]),
2258            record(vec![("a", int()), ("b", opt(string()))]),
2259            record(vec![("a", refined("Int", &["Positive"]))]),
2260            drecord(vec![("a", int()), ("b", int())], &["b"]),
2261            drecord(vec![("a", int()), ("b", string())], &["b"]),
2262            drecord(
2263                vec![("a", int()), ("b", refined("Int", &["Positive"]))],
2264                &["b"],
2265            ),
2266            drecord(vec![("a", int()), ("b", opt(int()))], &["b"]),
2267            drecord(vec![("a", int()), ("b", int())], &["a", "b"]),
2268            record(vec![(
2269                "a",
2270                drecord(vec![("x", int()), ("y", int())], &["y"]),
2271            )]),
2272            record(vec![("a", record(vec![("x", int())]))]),
2273            record(vec![("a", record(vec![("x", int()), ("y", opt(int()))]))]),
2274            sum(vec![("A", vec![]), ("B", vec![])]),
2275            sum(vec![("A", vec![])]),
2276            sum(vec![("A", vec![]), ("B", vec![]), ("C", vec![])]),
2277            sum(vec![("A", vec![("x", int())])]),
2278            sum(vec![("A", vec![("y", int())])]),
2279            sum(vec![("A", vec![("x", string())])]),
2280            sum(vec![("A", vec![("x", int()), ("y", string())])]),
2281            sum(vec![("A", vec![("y", string()), ("x", int())])]),
2282            sum(vec![("A", vec![("x", int()), ("y", opt(string()))])]),
2283            sum(vec![("A", vec![("x", int())]), ("B", vec![])]),
2284        ]
2285    }
2286
2287    fn response(ret: Shape) -> ServiceShape {
2288        ServiceShape {
2289            name: "probe".into(),
2290            params: Vec::new(),
2291            ret,
2292        }
2293    }
2294
2295    fn request(param: Shape) -> ServiceShape {
2296        ServiceShape {
2297            name: "probe".into(),
2298            params: vec![("p".into(), param)],
2299            ret: Shape::Base("Bool".into()),
2300        }
2301    }
2302
2303    /// The property, once per direction. Returns how many pairs were not
2304    /// breaking, so the test can tell it was not vacuous.
2305    fn sound(wrap: fn(Shape) -> ServiceShape, sender_is_callee: bool) -> usize {
2306        let pool = pool();
2307        let mut not_breaking = 0;
2308        for sender in &pool {
2309            for receiver in &pool {
2310                // A response flows callee to caller; a request, caller to callee.
2311                let (caller, callee) = if sender_is_callee {
2312                    (wrap(receiver.clone()), wrap(sender.clone()))
2313                } else {
2314                    (wrap(sender.clone()), wrap(receiver.clone()))
2315                };
2316                let verdict = check_call(&caller, &callee);
2317                if verdict.verdict == Verdict::Breaking {
2318                    continue;
2319                }
2320                not_breaking += 1;
2321                for v in values(sender, &[]) {
2322                    assert!(
2323                        decodes(receiver, &[], &v),
2324                        "the classifier called this compatible ({:?}), but the receiver refuses a value the sender can send:\n\
2325                         sender   {}\nreceiver {}\nvalue    {v:?}\n{:#?}",
2326                        verdict.verdict,
2327                        render(sender),
2328                        render(receiver),
2329                        verdict.findings,
2330                    );
2331                }
2332            }
2333        }
2334        not_breaking
2335    }
2336
2337    #[test]
2338    fn every_response_the_classifier_calls_compatible_decodes_at_the_caller() {
2339        let n = sound(response, true);
2340        assert!(
2341            n > 100,
2342            "only {n} compatible pairs: the property is close to vacuous"
2343        );
2344    }
2345
2346    #[test]
2347    fn every_request_the_classifier_calls_compatible_decodes_at_the_callee() {
2348        let n = sound(request, false);
2349        assert!(
2350            n > 100,
2351            "only {n} compatible pairs: the property is close to vacuous"
2352        );
2353    }
2354}