Skip to main content

bynk_check/
contract.rs

1//! v0.177 (#643): the canonical normal form of a cross-context contract, and
2//! its hash.
3//!
4//! A `workers` build compiles context A against context B's contract, and
5//! nothing at runtime checks that the *deployed* B still matches what A was
6//! compiled against — `deploy --context NAME` institutionalises the skew. The
7//! fix is to stamp a hash of the compiled contract beside `X-Bynk-Caller` and
8//! fail closed on mismatch (ADR 0092's pattern: a compile-time constant in a
9//! reserved header, metadata beside the payload, no crypto).
10//!
11//! The hash is only as good as the form it hashes. Two rules make it usable:
12//!
13//! 1. **Semantically-equal contracts must hash equal**, or a working deployment
14//!    409s spuriously — which is worse than no check at all, because it breaks
15//!    what worked and destroys trust in the mechanism. This is why the form is
16//!    canonical (predicates as a sorted set, record fields sorted by name)
17//!    rather than a rendering of source order.
18//! 2. **Both sides must canonicalise the *same* thing.** The callee's contract
19//!    is canonicalised **in the callee's own namespace**, from the callee's own
20//!    type table, on *both* sides — never in the caller's. The caller reaches
21//!    that table through `consumed_types[callee]` and the callee through its own
22//!    combined table; both are produced by the same `combined_types_for`, so the
23//!    two views cannot diverge by construction. A caller never canonicalises a
24//!    consumed type in its own namespace, where its rebranding would make the
25//!    same type render differently.
26
27use std::collections::{BTreeMap, HashMap};
28use std::fmt::Write as _;
29use std::sync::Arc;
30
31use bynk_syntax::ast::{Ident, PredKind, Refinement, TypeBody, TypeDecl, TypeRef};
32use bynk_syntax::span::Span;
33
34use crate::resolver::{CrossContextService, cross_context_service_for};
35use crate::symbols::UnitTable;
36use crate::unit_signature::{
37    CapabilityOpSignature, FnSignature, HandlerKindSignature, HandlerSignature,
38    MethodTableSignature, ParamSignature, ProtocolSignature, StoreFieldSignature, UnitSignature,
39};
40
41/// The canonical normal form of one `on call` service contract.
42///
43/// Shape: `<service>(<param>: <type>, …) -> <type>`. Parameter **names** and
44/// **order** are both included, and both are load-bearing rather than cosmetic:
45/// a multi-argument call sends an object keyed by parameter name, and a
46/// single-argument call sends the bare value — so a rename or a reorder is a
47/// genuine wire change, not a refactor.
48pub fn service_normal_form(
49    svc: &CrossContextService,
50    types: &HashMap<String, Arc<TypeDecl>>,
51) -> String {
52    let mut out = String::new();
53    let _ = write!(out, "{}(", svc.name);
54    for (i, (pname, pty)) in svc.params.iter().enumerate() {
55        if i > 0 {
56            out.push_str(", ");
57        }
58        let _ = write!(out, "{pname}: {}", canon_type(pty, types, &mut Vec::new()));
59    }
60    let _ = write!(
61        out,
62        ") -> {}",
63        canon_type(&svc.return_type, types, &mut Vec::new())
64    );
65    out
66}
67
68/// The canonical form of a type *as it appears on the wire*.
69///
70/// A named type expands **structurally**, not by name alone: the wire carries
71/// the fields, so renaming a record field or changing a variant's payload is a
72/// contract change that a name-only form would miss entirely. The name is kept
73/// alongside the structure because Bynk's types are nominal — swapping
74/// `AuthId` for a structurally identical `SessionId` changes the contract even
75/// though the bytes are unchanged. Keeping the name costs nothing in false
76/// positives: a rename already breaks the consumer's *compile*, so it cannot
77/// reach a deploy without the consumer being rebuilt too.
78fn canon_type(
79    t: &TypeRef,
80    types: &HashMap<String, Arc<TypeDecl>>,
81    seen: &mut Vec<String>,
82) -> String {
83    canon_type_in(t, types, seen, &HashMap::new(), Mode::Contract)
84}
85
86/// `subst` binds a generic declaration's type-parameter **names** to the
87/// canonical form of the concrete argument supplied at the use site.
88///
89/// A generic body MUST expand with its parameters substituted, or the
90/// parameter's *name* leaks into the form: `type Page[T] = { items: List[T] }`
91/// and the same declaration spelled with `U` are the same type with the same
92/// wire shape, but would hash differently. Across a deploy that renames a type
93/// parameter — a pure refactor with no wire consequence — every call would 409.
94/// That is the same class of spurious failure the sorted fields and the
95/// predicate set exist to prevent, and it is the one the module's own standard
96/// ("semantically-equal contracts must hash equal") forbids.
97fn canon_type_in(
98    t: &TypeRef,
99    types: &HashMap<String, Arc<TypeDecl>>,
100    seen: &mut Vec<String>,
101    subst: &HashMap<String, String>,
102    mode: Mode,
103) -> String {
104    match t {
105        TypeRef::Base(b, _) => b.name().to_string(),
106        TypeRef::Unit(_) => "()".to_string(),
107        // An `Effect` wraps the handler, not the payload — the caller awaits the
108        // promise, so it is not part of the wire contract.
109        TypeRef::Effect(inner, _) => canon_type_in(inner, types, seen, subst, mode),
110        TypeRef::List(a, _) => format!("List[{}]", canon_type_in(a, types, seen, subst, mode)),
111        TypeRef::Set(a, _) => format!("Set[{}]", canon_type_in(a, types, seen, subst, mode)),
112        TypeRef::Option(a, _) => format!("Option[{}]", canon_type_in(a, types, seen, subst, mode)),
113        TypeRef::Result(a, b, _) => format!(
114            "Result[{}, {}]",
115            canon_type_in(a, types, seen, subst, mode),
116            canon_type_in(b, types, seen, subst, mode)
117        ),
118        TypeRef::Map(k, v, _) => format!(
119            "Map[{}, {}]",
120            canon_type_in(k, types, seen, subst, mode),
121            canon_type_in(v, types, seen, subst, mode)
122        ),
123        // Generic-record instantiation: the arguments are positional, so their
124        // order *is* semantic and is preserved (unlike a record's fields).
125        TypeRef::App { name, args, .. } => {
126            let inner: Vec<String> = args
127                .iter()
128                .map(|a| canon_type_in(a, types, seen, subst, mode))
129                .collect();
130            // Bind the declaration's parameters to these arguments so the body
131            // expands over concrete types and the parameter's name never reaches
132            // the form.
133            let bound: HashMap<String, String> = types
134                .get(&name.name)
135                .map(|d| {
136                    d.type_params
137                        .iter()
138                        .zip(&inner)
139                        .map(|(p, a)| (p.name.name.clone(), a.clone()))
140                        .collect()
141                })
142                .unwrap_or_default();
143            let head = canon_named_in(&name.name, types, seen, &bound, mode);
144            format!("{head}[{}]", inner.join(", "))
145        }
146        TypeRef::Named(id) => {
147            // A bound type parameter renders as the argument it stands for.
148            match subst.get(&id.name) {
149                Some(bound) => bound.clone(),
150                None => canon_named_in(&id.name, types, seen, subst, mode),
151            }
152        }
153        TypeRef::HttpResult(a, _) => {
154            format!("HttpResult[{}]", canon_type_in(a, types, seen, subst, mode))
155        }
156        TypeRef::ValidationError(_) => "ValidationError".to_string(),
157        TypeRef::DecodeError(_) => "DecodeError".to_string(),
158        TypeRef::QueueResult(_) => "QueueResult".to_string(),
159        TypeRef::Asset(_) => "Asset".to_string(),
160        TypeRef::RequestHeaders(_) => "RequestHeaders".to_string(),
161        TypeRef::RequestQuery(_) => "RequestQuery".to_string(),
162        TypeRef::RequestCookies(_) => "RequestCookies".to_string(),
163        TypeRef::TokenClaims(_) => "TokenClaims".to_string(),
164        TypeRef::BoundaryRejection(_) => "BoundaryRejection".to_string(),
165        // The confined family is rejected at every boundary, so it cannot appear
166        // in a contract. Render it rather than panic: the normal form is also a
167        // diagnostic surface, and a compiler bug should not become a crash here.
168        TypeRef::Fn(..)
169        | TypeRef::Query(..)
170        | TypeRef::Stream(..)
171        | TypeRef::Connection(..)
172        | TypeRef::History(..) => "<non-boundary>".to_string(),
173    }
174}
175
176fn canon_named_in(
177    name: &str,
178    types: &HashMap<String, Arc<TypeDecl>>,
179    seen: &mut Vec<String>,
180    subst: &HashMap<String, String>,
181    mode: Mode,
182) -> String {
183    // A recursive record terminates on the data, so its codec is finite and it
184    // is a legal contract — but its *expansion* is not. Emit a back-reference on
185    // revisit. `type Node = { next: Option[Node] }` canonicalises as
186    // `Node{next: Option[@Node]}` — the cycle is named, so two different
187    // recursive shapes still differ.
188    //
189    // The storage renderings carry no type names (#2204), so their
190    // back-reference is positional instead: `@N` points N enclosing named types
191    // out (de Bruijn style). `Node` and a renamed `Link` then both render
192    // `{next: Option[@1], v: Int}`, while two different cycles still differ.
193    // `seen` is the stack of named types being expanded, innermost last.
194    if let Some(at) = seen.iter().position(|n| n == name) {
195        return match mode {
196            Mode::Contract => format!("@{name}"),
197            Mode::StorageStructure | Mode::StorageFull => format!("@{}", seen.len() - at),
198        };
199    }
200    seen.push(name.to_string());
201    let Some(decl) = types.get(name) else {
202        // Not in the callee's table: a runtime- or compiler-known name with no
203        // declaration to expand. The name alone is the whole contract for it.
204        seen.pop();
205        return name.to_string();
206    };
207    let body = match &decl.body {
208        // Record fields sort by name: a JSON object is unordered, so field
209        // *order* is not wire-observable and must not perturb the hash — while
210        // field *presence* and type are exactly what the hash exists to pin.
211        //
212        // #1969: an inline refinement is part of the field's type, so it is
213        // part of the form (`qty: Int where Positive`), canonicalised as a
214        // sorted set exactly like a named refined type's. The decoder checks
215        // it, so a callee that tightens it rejects values its callers send.
216        TypeBody::Record(r) => {
217            let mut fields: Vec<String> = r
218                .fields
219                .iter()
220                .map(|f| {
221                    let ty = canon_type_in(&f.type_ref, types, seen, subst, mode);
222                    match f.refinement.as_ref().filter(|_| mode.keeps_predicates()) {
223                        Some(r) => format!("{}: {ty} {}", f.name.name, canon_refinement(Some(r))),
224                        None => format!("{}: {ty}", f.name.name),
225                    }
226                })
227                .collect();
228            fields.sort();
229            format!("{{{}}}", fields.join(", "))
230        }
231        // Variants sort by name for the same reason: the wire carries a `kind`
232        // discriminant, so declaration order is invisible to it.
233        TypeBody::Sum(s) => {
234            let mut variants: Vec<String> = s
235                .variants
236                .iter()
237                .map(|v| {
238                    // A payload is keyed by field name on the wire
239                    // (`{"kind":"Circle","radius":0.5}`), so in every mode it
240                    // renders as a record would: `name: type`, sorted, since
241                    // JSON object order is not observable. Positional order is
242                    // therefore invisible, while a renamed field is a wire break.
243                    let mut payload: Vec<String> = v
244                        .payload
245                        .iter()
246                        .map(|p| {
247                            let ty = canon_type_in(&p.type_ref, types, seen, subst, mode);
248                            format!("{}: {ty}", p.name.name)
249                        })
250                        .collect();
251                    payload.sort();
252                    if payload.is_empty() {
253                        v.name.name.clone()
254                    } else {
255                        format!("{}({})", v.name.name, payload.join(", "))
256                    }
257                })
258                .collect();
259            variants.sort();
260            format!("|{}", variants.join("|"))
261        }
262        TypeBody::Refined {
263            base, refinement, ..
264        } => {
265            if mode.keeps_predicates() {
266                format!("{} {}", base.name(), canon_refinement(refinement.as_ref()))
267            } else {
268                base.name().to_string()
269            }
270        }
271        // In the **contract** form, an opaque type's predicate is deliberately
272        // excluded — only its representation is part of the contract.
273        //
274        // The consumer cannot see the predicate by construction (that is what
275        // `exports opaque` means), so no consumer behaviour can depend on it: it
276        // can hold and pass an `AuthId`, never inspect or mint one. Including the
277        // predicate would therefore manufacture skew failures between two
278        // contexts that cannot disagree — the owner tightening `Matches(...)`
279        // would 409 every caller for a change none of them can observe. This is
280        // the same position ADR 0199 took on opacity, from the same premise.
281        //
282        // Stored state is the other way round (state-migrations S0, #2204): the
283        // owner re-validates its own opaque values on rehydration, so a
284        // tightened opaque predicate *is* observable there, and the full
285        // storage rendering keeps it. The stored bytes are just the base, so
286        // neither storage rendering marks opacity.
287        TypeBody::Opaque {
288            base, refinement, ..
289        } => match mode {
290            Mode::Contract => format!("{} opaque", base.name()),
291            Mode::StorageStructure => base.name().to_string(),
292            Mode::StorageFull => {
293                format!("{} {}", base.name(), canon_refinement(refinement.as_ref()))
294            }
295        },
296    };
297    seen.pop();
298    match mode {
299        Mode::Contract => format!("{name}{body}"),
300        // Stored bytes carry no type names (records are keyed by field, sums
301        // tagged by variant), so renaming a type must not read as a retyped
302        // field. Recursion is anchored positionally (`@N` above), not by name.
303        Mode::StorageStructure | Mode::StorageFull => body,
304    }
305}
306
307/// Which canonical form a walk renders.
308#[derive(Clone, Copy, PartialEq, Eq, Debug)]
309enum Mode {
310    /// The cross-context contract form: nominal, refinements kept, opaque
311    /// predicates elided. Backs [`contract_hash`].
312    Contract,
313    /// A stored field's structure (state-migrations S0): structural, every
314    /// predicate stripped. A change here changes what is on disk.
315    StorageStructure,
316    /// A stored field's structure *and* refinements, opaque ones included. A
317    /// change here alone leaves the stored bytes readable.
318    StorageFull,
319}
320
321impl Mode {
322    fn keeps_predicates(self) -> bool {
323        !matches!(self, Mode::StorageStructure)
324    }
325}
326
327/// State-migrations S0 (#2204, track §3.1): the two canonical renderings of a
328/// stored type that `bynk.schema.lock`'s `[agents]` table records — the
329/// structure (`.0`, predicates stripped) and the full form (`.1`, predicates
330/// kept, opaque ones included). Both expand named records and sums
331/// structurally and sort fields and variants by name, as the contract form
332/// does. Unlike it, they carry no type names, because stored bytes carry none:
333/// recursion closes with a positional `@N` back-reference instead of `@Name`,
334/// and a sum payload renders like a record (`name: type`, sorted), because a
335/// stored payload is keyed by field name.
336pub fn canon_storage_type(t: &TypeRef, types: &HashMap<String, Arc<TypeDecl>>) -> (String, String) {
337    let render = |mode| canon_type_in(t, types, &mut Vec::new(), &HashMap::new(), mode);
338    (render(Mode::StorageStructure), render(Mode::StorageFull))
339}
340
341/// #2676 (Decision B): every position in a stored value of type `t`, as
342/// `(path, shallow structure, has a default)`, starting from `prefix` (the
343/// `store` field's name). It expands exactly what [`canon_storage_type`]'s
344/// structure does (records and sums by field and variant name, containers by
345/// their element, recursion closed by `@N`), but node by node, so two values
346/// have the same structure exactly when their path sets agree. That lets the
347/// schema reconcile see *where* a change is, and admit only a record field
348/// added with a default.
349pub fn storage_paths(
350    t: &TypeRef,
351    prefix: &str,
352    types: &HashMap<String, Arc<TypeDecl>>,
353) -> Vec<StoragePath> {
354    let mut out = Vec::new();
355    paths_in(t, prefix, false, None, types, &mut Vec::new(), &mut out);
356    out.sort_by(|a, b| a.path.cmp(&b.path));
357    out
358}
359
360/// One position [`storage_paths`] yields: its path, its shallow structure,
361/// the same with predicates kept, and whether it is a record field that
362/// declares a default.
363#[derive(Debug, Clone, PartialEq, Eq)]
364pub struct StoragePath {
365    pub path: String,
366    pub structure: String,
367    pub full: String,
368    pub default: bool,
369}
370
371#[allow(clippy::too_many_arguments)]
372fn paths_in(
373    t: &TypeRef,
374    path: &str,
375    default: bool,
376    // A record field's inline refinement, which belongs to the field's node.
377    inline: Option<&Refinement>,
378    types: &HashMap<String, Arc<TypeDecl>>,
379    seen: &mut Vec<String>,
380    out: &mut Vec<StoragePath>,
381) {
382    let with_inline = |full: String| match inline {
383        Some(r) => format!("{full} {}", canon_refinement(Some(r))),
384        None => full,
385    };
386    // A container or a record/sum node: its predicates live on its children.
387    let node = |ty: String, out: &mut Vec<StoragePath>| {
388        out.push(StoragePath {
389            path: path.to_string(),
390            full: with_inline(ty.clone()),
391            structure: ty,
392            default,
393        });
394    };
395    // A leaf: both renderings of the whole type.
396    let leaf = |out: &mut Vec<StoragePath>| {
397        let (structure, full) = canon_storage_type(t, types);
398        out.push(StoragePath {
399            path: path.to_string(),
400            full: with_inline(full),
401            structure,
402            default,
403        });
404    };
405    match t {
406        TypeRef::Effect(inner, _) => paths_in(inner, path, default, inline, types, seen, out),
407        TypeRef::List(a, _) => {
408            node("List".to_string(), out);
409            paths_in(a, &format!("{path}[]"), false, None, types, seen, out);
410        }
411        TypeRef::Set(a, _) => {
412            node("Set".to_string(), out);
413            paths_in(a, &format!("{path}[]"), false, None, types, seen, out);
414        }
415        TypeRef::Option(a, _) => {
416            node("Option".to_string(), out);
417            paths_in(a, &format!("{path}?"), false, None, types, seen, out);
418        }
419        TypeRef::Result(a, b, _) => {
420            node("Result".to_string(), out);
421            paths_in(a, &format!("{path}|Ok"), false, None, types, seen, out);
422            paths_in(b, &format!("{path}|Err"), false, None, types, seen, out);
423        }
424        TypeRef::Map(k, v, _) => {
425            // A key is text on disk, so it has no positions of its own: its
426            // whole structure is part of the map node.
427            node(format!("Map[{}]", canon_storage_type(k, types).0), out);
428            paths_in(v, &format!("{path}{{}}"), false, None, types, seen, out);
429        }
430        TypeRef::Named(id) => {
431            let name = id.name.as_str();
432            let Some(decl) = types.get(name) else {
433                return leaf(out);
434            };
435            match &decl.body {
436                TypeBody::Record(r) => {
437                    let fields: Vec<StoredField> = r
438                        .fields
439                        .iter()
440                        .map(|f| StoredField {
441                            name: f.name.name.clone(),
442                            ty: f.type_ref.clone(),
443                            default: f.init.is_some(),
444                            inline: f.refinement.clone(),
445                        })
446                        .collect();
447                    record_paths(name, &fields, path, default, types, seen, out);
448                }
449                TypeBody::Sum(s) => {
450                    let variants: Vec<(String, Vec<(String, TypeRef)>)> = s
451                        .variants
452                        .iter()
453                        .map(|v| {
454                            let payload = v
455                                .payload
456                                .iter()
457                                .map(|p| (p.name.name.clone(), p.type_ref.clone()))
458                                .collect();
459                            (v.name.name.clone(), payload)
460                        })
461                        .collect();
462                    sum_paths(name, &variants, path, default, types, seen, out);
463                }
464                // A refined or opaque type is its base on disk.
465                TypeBody::Refined { .. } | TypeBody::Opaque { .. } => leaf(out),
466            }
467        }
468        TypeRef::App { name, args, .. } => {
469            let name = name.name.as_str();
470            if let Some(fields) = crate::wire::record_inst_fields(name, args, types) {
471                // The instantiation substitutes each field's type; its
472                // default and inline refinement are the declaration's.
473                let declared: HashMap<&str, (bool, Option<Refinement>)> =
474                    match types.get(name).map(|d| &d.body) {
475                        Some(TypeBody::Record(r)) => r
476                            .fields
477                            .iter()
478                            .map(|f| {
479                                (
480                                    f.name.name.as_str(),
481                                    (f.init.is_some(), f.refinement.clone()),
482                                )
483                            })
484                            .collect(),
485                        _ => HashMap::new(),
486                    };
487                let fields: Vec<StoredField> = fields
488                    .into_iter()
489                    .map(|(n, ty)| {
490                        let (default, inline) =
491                            declared.get(n.as_str()).cloned().unwrap_or_default();
492                        StoredField {
493                            name: n,
494                            ty,
495                            default,
496                            inline,
497                        }
498                    })
499                    .collect();
500                record_paths(name, &fields, path, default, types, seen, out);
501            } else if let Some(variants) = crate::wire::sum_inst_variants(name, args, types) {
502                sum_paths(name, &variants, path, default, types, seen, out);
503            } else {
504                leaf(out);
505            }
506        }
507        _ => leaf(out),
508    }
509}
510
511/// A record field as the path walk sees it.
512struct StoredField {
513    name: String,
514    ty: TypeRef,
515    default: bool,
516    inline: Option<Refinement>,
517}
518
519/// The back-reference [`canon_named_in`] writes on revisiting `name`, if it is
520/// already being expanded.
521fn storage_back_reference(name: &str, seen: &[String]) -> Option<String> {
522    seen.iter()
523        .position(|n| n == name)
524        .map(|at| format!("@{}", seen.len() - at))
525}
526
527fn record_paths(
528    name: &str,
529    fields: &[StoredField],
530    path: &str,
531    default: bool,
532    types: &HashMap<String, Arc<TypeDecl>>,
533    seen: &mut Vec<String>,
534    out: &mut Vec<StoragePath>,
535) {
536    if let Some(back) = storage_back_reference(name, seen) {
537        out.push(StoragePath {
538            path: path.to_string(),
539            full: back.clone(),
540            structure: back,
541            default,
542        });
543        return;
544    }
545    out.push(StoragePath {
546        path: path.to_string(),
547        structure: "{}".to_string(),
548        full: "{}".to_string(),
549        default,
550    });
551    seen.push(name.to_string());
552    for f in fields {
553        let at = format!("{path}.{}", f.name);
554        paths_in(&f.ty, &at, f.default, f.inline.as_ref(), types, seen, out);
555    }
556    seen.pop();
557}
558
559fn sum_paths(
560    name: &str,
561    variants: &[(String, Vec<(String, TypeRef)>)],
562    path: &str,
563    default: bool,
564    types: &HashMap<String, Arc<TypeDecl>>,
565    seen: &mut Vec<String>,
566    out: &mut Vec<StoragePath>,
567) {
568    if let Some(back) = storage_back_reference(name, seen) {
569        out.push(StoragePath {
570            path: path.to_string(),
571            full: back.clone(),
572            structure: back,
573            default,
574        });
575        return;
576    }
577    out.push(StoragePath {
578        path: path.to_string(),
579        structure: "|".to_string(),
580        full: "|".to_string(),
581        default,
582    });
583    seen.push(name.to_string());
584    for (variant, payload) in variants {
585        let at = format!("{path}|{variant}");
586        out.push(StoragePath {
587            path: at.clone(),
588            structure: "variant".to_string(),
589            full: "variant".to_string(),
590            default: false,
591        });
592        for (field, ty) in payload {
593            paths_in(ty, &format!("{at}.{field}"), false, None, types, seen, out);
594        }
595    }
596    seen.pop();
597}
598
599/// Predicates canonicalise as a **sorted set**.
600///
601/// This is not a nicety adjacent to the hash; it is a precondition for it.
602/// Predicates are conjunctive and side-effect-free, so `String where NonEmpty,
603/// MaxLen(10)` and `String where MaxLen(10), NonEmpty` are the *same type* — and
604/// hashing them in source order would make two contexts that agree perfectly
605/// fail closed against each other. The same normal form also backs the checker's
606/// `refinements_match`, so the matcher and the hash cannot disagree about what
607/// "the same refinement" means.
608pub fn canon_refinement(r: Option<&Refinement>) -> String {
609    let Some(r) = r else {
610        return String::new();
611    };
612    format!("where {}", canon_pred_set(r).join(", "))
613}
614
615/// The sorted, de-duplicated canonical predicates of one refinement — the set
616/// [`canon_refinement`] joins, kept as a list for the compatibility classifier
617/// (`contract_compat`), which compares predicates rather than text.
618pub(crate) fn canon_pred_set(r: &Refinement) -> Vec<String> {
619    let mut preds: Vec<String> = r
620        .predicates
621        .iter()
622        .map(|p| canon_predicate(&p.kind))
623        .collect();
624    preds.sort();
625    preds.dedup();
626    preds
627}
628
629pub fn canon_predicate(p: &PredKind) -> String {
630    match p {
631        PredKind::Matches(s) => format!("Matches({s:?})"),
632        // Bounds keep their source lexemes elsewhere (byte-stable emission), but
633        // a contract is about *values*: `1` and `01` are the same bound, so the
634        // parsed value is what canonicalises.
635        PredKind::InRange(a, b) => format!("InRange({}, {})", a.value, b.value),
636        PredKind::InRangeF(a, b) => format!("InRangeF({}, {})", a.value, b.value),
637        PredKind::InRangeD(a, b) => format!(
638            "InRangeD({}, {})",
639            bynk_syntax::decimal::canonical(&a.coef, a.scale),
640            bynk_syntax::decimal::canonical(&b.coef, b.scale)
641        ),
642        PredKind::MinLength(n) => format!("MinLength({n})"),
643        PredKind::MaxLength(n) => format!("MaxLength({n})"),
644        PredKind::Length(n) => format!("Length({n})"),
645        // R12.2 names these as sugar for `InRange(0, ∞)`/`InRange(1, ∞)`, but the
646        // fold stays undone (#1049): neither base has a writable literal bound
647        // that stands for `∞` — the lexer rejects any float literal that would
648        // parse to infinity, and `Int`'s `i64::MAX` is a real, arbitrary finite
649        // bound, not the language's spelling of "unbounded". Folding onto an
650        // invented string nothing else can produce would only rename the
651        // literal, at the cost of a contract-hash change for every boundary
652        // type carrying one. Revisit alongside R12.3 (entailment), which is
653        // the actual consumer of a normalised Interval domain.
654        PredKind::NonNegative => "NonNegative".to_string(),
655        PredKind::Positive => "Positive".to_string(),
656        // `NonEmpty` is sugar for `MinLength(1)` (R12.2) — folding it here makes
657        // `String where NonEmpty` and `String where MinLength(1)` the same
658        // canonical form, so `service_contract_hash` and `refinements_match`
659        // agree that they are the same type. Unconditional: `NonEmpty` only
660        // ever applies to `BaseType::String` (`refinements.rs`'s
661        // `pred_applies_to`), so no base needs threading through here.
662        PredKind::NonEmpty => "MinLength(1)".to_string(),
663        // #2867: its own canonical form; `entailment` knows it implies `Length(10)`.
664        PredKind::IsoDate => "IsoDate".to_string(),
665        // #3873: its own canonical form; `entailment` knows it implies `MinLength(9)`.
666        PredKind::Cron => "Cron".to_string(),
667    }
668}
669
670/// FNV-1a (64-bit) over the canonical form, rendered as 16 lowercase hex chars.
671///
672/// **Why not a cryptographic hash.** Trust here is static and channel-based, and
673/// this increment does not change that (ADR 0092): `/_bynk/call/` is
674/// platform-dispatched and not externally routable, every context in a
675/// deployment is one trust domain, and a malicious first-party context is out of
676/// the threat model. This is a **skew detector, not a security control** — an
677/// accident detector. Forging it buys an attacker nothing they could not already
678/// do, so `sha2`'s ~6-crate dependency tree would buy nothing either. A
679/// collision degrades to *today's* behaviour for that one pair (an undetected
680/// skew), not to something worse, and at ~1e-14 for a 1000-contract project it
681/// is not the risk worth engineering against.
682///
683/// **Why hand-rolled.** `std::collections::hash_map::DefaultHasher` is
684/// explicitly not stable across Rust releases, so it cannot back a value that
685/// crosses a wire or is compared between two separately-compiled binaries. FNV-1a
686/// is fully specified, so two compilers agree forever.
687pub fn contract_hash(normal_form: &str) -> String {
688    fnv1a64_hex(normal_form.as_bytes())
689}
690
691/// FNV-1a 64-bit offset basis. Published in the wire-format reference (#1969).
692pub const FNV1A64_OFFSET: u64 = 0xcbf2_9ce4_8422_2325;
693/// FNV-1a 64-bit prime. Published in the wire-format reference (#1969).
694pub const FNV1A64_PRIME: u64 = 0x0000_0100_0000_01b3;
695
696/// FNV-1a (64-bit) over `bytes`, as 16 lowercase hex chars — [`contract_hash`]'s
697/// algorithm over raw bytes. #1883, slice 1b also uses it for an asset's
698/// content hash (`assets::served_path`), where the same reasoning holds: it
699/// only has to tell one project's own files apart, reproducibly.
700pub fn fnv1a64_hex(bytes: &[u8]) -> String {
701    let mut h = FNV1A64_OFFSET;
702    for b in bytes {
703        h ^= *b as u64;
704        h = h.wrapping_mul(FNV1A64_PRIME);
705    }
706    format!("{h:016x}")
707}
708
709/// What a client of one `from http` route acts on: the facts [`http_route_normal_form`]
710/// canonicalises. #3508 (BC6) hashes it so a generated client can name the contract it
711/// was made for, and a log or a deploy gate can compare it.
712///
713/// Unlike an `on call` contract this one is **informational**: nothing rejects a
714/// mismatch. A public HTTP API's browsers and cached bundles lag the server for days,
715/// so a hard refusal would turn every additive deploy into an outage; the hash exists
716/// to be compared, logged and sent, never enforced.
717#[derive(Debug, Clone)]
718pub struct HttpRouteContract {
719    /// `GET`, `POST`, ...
720    pub method: String,
721    /// `/orders/:id`.
722    pub path: String,
723    /// What the caller supplies, in the order the client takes it.
724    pub params: Vec<HttpRouteParam>,
725    /// The declared success type, when it carries a value.
726    pub success: Option<TypeRef>,
727    /// Each answer as `(status, variant, payload kind)`, in any order.
728    pub replies: Vec<(u16, String, String)>,
729}
730
731/// One thing a caller supplies to a route.
732#[derive(Debug, Clone)]
733pub struct HttpRouteParam {
734    /// `path`, `query`, `cookies`, `body-json`, `body-form`, `body-multipart` or `body-raw`.
735    pub kind: String,
736    /// The handler's parameter name.
737    pub name: String,
738    /// Its type; `None` for a `@raw` body, whose content type is `detail`.
739    pub ty: Option<TypeRef>,
740    /// The `@raw` content type, when the kind is `body-raw`.
741    pub detail: Option<String>,
742}
743
744/// The canonical normal form of one `from http` route, as a client sees it.
745///
746/// Every type is canonicalised as it appears on the wire (the same `canon_type` the
747/// `on call` contract uses, so a record's fields are sorted, predicates are a set and
748/// a generic is substituted), in the namespace of the route's own service. The
749/// replies are a sorted set. What is *not* in it is what a client does not act on: a
750/// handler's body, a doc comment, the order of a record's fields, the route's CORS
751/// policy and its plain-JSON `Option` mode (the client reads both forms).
752pub fn http_route_normal_form(
753    route: &HttpRouteContract,
754    types: &HashMap<String, Arc<TypeDecl>>,
755) -> String {
756    let mut out = format!("{} {}", route.method, route.path);
757    for p in &route.params {
758        let shape = match (&p.ty, &p.detail) {
759            (Some(t), _) => canon_type(t, types, &mut Vec::new()),
760            (None, Some(d)) => d.clone(),
761            (None, None) => String::new(),
762        };
763        let _ = write!(out, " | {} {}: {shape}", p.kind, p.name);
764    }
765    match &route.success {
766        Some(t) => {
767            let _ = write!(out, " | ok: {}", canon_type(t, types, &mut Vec::new()));
768        }
769        None => out.push_str(" | ok: none"),
770    }
771    let mut replies: Vec<String> = route
772        .replies
773        .iter()
774        .map(|(status, variant, payload)| format!("{status}:{variant}:{payload}"))
775        .collect();
776    replies.sort();
777    replies.dedup();
778    let _ = write!(out, " | replies: {}", replies.join(","));
779    out
780}
781
782/// The hash of one route's normal form: FNV-1a, as [`contract_hash`].
783pub fn http_route_contract_hash(
784    route: &HttpRouteContract,
785    types: &HashMap<String, Arc<TypeDecl>>,
786) -> String {
787    contract_hash(&http_route_normal_form(route, types))
788}
789
790/// A service's hash: the hash of its routes' hashes, sorted, so the order the routes
791/// are declared in does not move it.
792pub fn http_service_contract_hash(route_hashes: &[String]) -> String {
793    let mut sorted: Vec<&str> = route_hashes.iter().map(String::as_str).collect();
794    sorted.sort_unstable();
795    contract_hash(&sorted.join("\n"))
796}
797
798/// The stamped contract hash for one consumed service.
799pub fn service_contract_hash(
800    svc: &CrossContextService,
801    types: &HashMap<String, Arc<TypeDecl>>,
802) -> String {
803    contract_hash(&service_normal_form(svc, types))
804}
805
806/// v0.177 (#643): a context's own `on call` contract hashes, keyed by service
807/// name — the constants its Worker entry compares an incoming
808/// `X-Bynk-Contract` against.
809///
810/// Built by projecting each local `on call` handler into the **same**
811/// [`CrossContextService`] shape [`crate::symbols::build_cross_context_info`]
812/// hands a *caller* for the same service, via the one shared projection
813/// [`cross_context_service_for`], and hashing it from the same combined type
814/// table. That symmetry is the whole correctness argument: a caller and a
815/// callee compiled from one source tree must agree, or the check fires on
816/// every call instead of only on real skew — sharing the projection makes the
817/// agreement structural rather than two hand-written copies staying in sync
818/// by convention.
819pub fn own_contract_hashes(
820    table: &UnitTable,
821    own_types: &HashMap<String, Arc<TypeDecl>>,
822) -> BTreeMap<String, String> {
823    let mut out = BTreeMap::new();
824    for (sname, sdecl) in &table.services {
825        let Some(svc) = cross_context_service_for(sname, sdecl) else {
826            continue;
827        };
828        out.insert(sname.clone(), service_contract_hash(&svc, own_types));
829    }
830    out
831}
832
833/// P8.1 (#1512, [DECISION C]): the canonical form of a body-free parameter
834/// list — shared by [`canon_fn_signature`] and [`canon_handler_signature`] so
835/// the two categories can't drift on how a parameter renders.
836fn canon_params(params: &[ParamSignature], types: &HashMap<String, Arc<TypeDecl>>) -> String {
837    let mut out = String::new();
838    for (i, p) in params.iter().enumerate() {
839        if i > 0 {
840            out.push_str(", ");
841        }
842        let _ = write!(
843            out,
844            "{}: {}",
845            p.name,
846            canon_type(&p.type_ref, types, &mut Vec::new())
847        );
848    }
849    out
850}
851
852/// P8.1 (#1512, [DECISION C]): the canonical form of a [`FnSignature`] —
853/// extends this module's own `canon_type` (ADR 0200) to a shape it doesn't
854/// reach today. Body-free by construction ([DECISION B]): there is no
855/// `body`/`requires`/`ensures` field on `FnSignature` to accidentally
856/// include here.
857pub fn canon_fn_signature(f: &FnSignature, types: &HashMap<String, Arc<TypeDecl>>) -> String {
858    let mut out = String::new();
859    let _ = write!(out, "fn {}", f.name);
860    if !f.type_params.is_empty() {
861        let _ = write!(out, "[{}]", f.type_params.join(", "));
862    }
863    let _ = write!(out, "({})", canon_params(&f.params, types));
864    let _ = write!(
865        out,
866        " -> {}",
867        canon_type(&f.return_type, types, &mut Vec::new())
868    );
869    if !f.where_bounds.is_empty() {
870        let _ = write!(out, " where {}", f.where_bounds.join(", "));
871    }
872    if f.has_self {
873        out.push_str(" self");
874    }
875    out
876}
877
878/// P8.1 (#1512, [DECISION C]): the canonical form of a [`HandlerKindSignature`].
879/// Added alongside the rest of [`canon_handler_signature`] by PR #1517's own
880/// bot review (finding #1) — every field here is already a plain value
881/// (`HttpMethod`'s own rendered name, a route/cron `String`), so nothing
882/// needs excluding beyond the enum discriminant itself carrying no `Span`.
883fn canon_handler_kind(k: &HandlerKindSignature) -> String {
884    match k {
885        HandlerKindSignature::Call => "call".to_string(),
886        HandlerKindSignature::Http { method, path } => format!("http {method} {path:?}"),
887        HandlerKindSignature::Cron { expr } => format!("cron {expr:?}"),
888        HandlerKindSignature::Message => "message".to_string(),
889        HandlerKindSignature::Open => "open".to_string(),
890        HandlerKindSignature::Close => "close".to_string(),
891        HandlerKindSignature::Event => "event".to_string(),
892        HandlerKindSignature::Rejected => "rejected".to_string(),
893    }
894}
895
896/// P8.1 (#1512, [DECISION C]): the canonical form of a [`HandlerSignature`].
897/// `given` renders sorted — its rendered `CapRef` names have no meaningful
898/// order to preserve (it's a set, not a sequence). `kind` is rendered first
899/// (PR #1517's own bot review, finding #1) — two handlers that differ only
900/// in HTTP method or route, or in `on call` vs. `on message`, must not
901/// canonicalise identically.
902pub fn canon_handler_signature(
903    h: &HandlerSignature,
904    types: &HashMap<String, Arc<TypeDecl>>,
905) -> String {
906    let mut out = String::new();
907    let _ = write!(out, "on {}", canon_handler_kind(&h.kind));
908    if let Some(m) = &h.method_name {
909        let _ = write!(out, " {m}");
910    }
911    let _ = write!(out, "({})", canon_params(&h.params, types));
912    let _ = write!(
913        out,
914        " -> {}",
915        canon_type(&h.return_type, types, &mut Vec::new())
916    );
917    if !h.given.is_empty() {
918        let mut given = h.given.clone();
919        given.sort();
920        let _ = write!(out, " given {}", given.join(", "));
921    }
922    out
923}
924
925/// P8.1 (#1512, [DECISION C]): the canonical form of a [`CapabilityOpSignature`]
926/// — added by PR #1517's own bot review (finding #3): a `capability`
927/// declaration's own ops are the abstract signature a consumer's
928/// `Cap.op(...)` call site compiles against.
929pub fn canon_capability_op_signature(
930    op: &CapabilityOpSignature,
931    types: &HashMap<String, Arc<TypeDecl>>,
932) -> String {
933    let mut out = String::new();
934    let _ = write!(out, "fn {}", op.name);
935    if !op.type_params.is_empty() {
936        let _ = write!(out, "[{}]", op.type_params.join(", "));
937    }
938    let _ = write!(out, "({})", canon_params(&op.params, types));
939    let _ = write!(
940        out,
941        " -> {}",
942        canon_type(&op.return_type, types, &mut Vec::new())
943    );
944    out
945}
946
947/// P8.1 (#1512, [DECISION C]): the canonical form of a [`ProtocolSignature`]
948/// — added by PR #1517's own bot review ("worth a look"): `from http` vs.
949/// `from queue(...)` vs. `from websocket(...)` changes a service's entire
950/// external surface. `Events`' own `pattern`/`schema_dispatch` render only as
951/// presence (see `unit_signature.rs`'s own module doc comment for why).
952fn canon_protocol_signature(
953    p: &ProtocolSignature,
954    types: &HashMap<String, Arc<TypeDecl>>,
955) -> String {
956    match p {
957        ProtocolSignature::Call => "call".to_string(),
958        ProtocolSignature::Http => "http".to_string(),
959        ProtocolSignature::Cron => "cron".to_string(),
960        ProtocolSignature::Queue { name } => format!("queue {name:?}"),
961        ProtocolSignature::Email { address } => format!("email {address:?}"),
962        ProtocolSignature::WebSocket { in_type, out_type } => format!(
963            "websocket in={} out={}",
964            canon_type(in_type, types, &mut Vec::new()),
965            canon_type(out_type, types, &mut Vec::new())
966        ),
967        ProtocolSignature::Events {
968            event_type,
969            has_pattern,
970            has_schema_dispatch,
971        } => format!(
972            "events {} pattern={has_pattern} schema_dispatch={has_schema_dispatch}",
973            canon_type(event_type, types, &mut Vec::new())
974        ),
975    }
976}
977
978/// P8.1 (#1512, [DECISION C]): the canonical form of a [`StoreFieldSignature`].
979pub fn canon_store_field_signature(
980    f: &StoreFieldSignature,
981    types: &HashMap<String, Arc<TypeDecl>>,
982) -> String {
983    let mut out = String::new();
984    let _ = write!(out, "{}: {}", f.name, f.kind_head);
985    if !f.kind_args.is_empty() {
986        let args: Vec<String> = f
987            .kind_args
988            .iter()
989            .map(|a| canon_type(a, types, &mut Vec::new()))
990            .collect();
991        let _ = write!(out, "[{}]", args.join(", "));
992    }
993    out
994}
995
996/// P8.1 (#1512, [DECISION C]): the canonical form of a unit's own combined
997/// type table — the cross-context-types category, `combined_types_for`'s
998/// output reused unchanged. Each named type expands structurally via
999/// [`canon_named_in`] (through a synthetic, zero-span [`TypeRef::Named`] —
1000/// spans are erased by every canonical renderer in this module already, so a
1001/// dummy span here carries no information loss), sorted by name so map
1002/// iteration order can't perturb the rendering.
1003fn canon_types_table(types: &HashMap<String, Arc<TypeDecl>>) -> String {
1004    let mut names: Vec<&String> = types.keys().collect();
1005    names.sort();
1006    let mut out = String::new();
1007    for name in names {
1008        let named = TypeRef::Named(Ident {
1009            name: name.clone(),
1010            span: Span::new(0, 0),
1011        });
1012        let _ = write!(
1013            out,
1014            "{}={};",
1015            name,
1016            canon_type(&named, types, &mut Vec::new())
1017        );
1018    }
1019    out
1020}
1021
1022/// P8.1 (#1512, [DECISION C]): [`UnitSignature::canonical`]'s own
1023/// implementation — the single rendering R3.14's own stability proof
1024/// compares. Every category is rendered sorted (by the caller's own
1025/// `BTreeMap`/`BTreeSet` keys, or an explicit sort for `Vec`-shaped fields
1026/// like a handler's own `given`), so construction order never perturbs the
1027/// form — the same "compare the canonical string, not map/vec iteration
1028/// order" discipline [`service_normal_form`]'s record-field sort already
1029/// established for ADR 0200.
1030pub fn canon_unit_signature(sig: &UnitSignature) -> String {
1031    let types = &sig.combined_types;
1032    let mut out = String::new();
1033    let _ = writeln!(out, "unit {}", sig.id.0);
1034    let _ = writeln!(out, "types: {}", canon_types_table(types));
1035
1036    out.push_str("fns:\n");
1037    for f in sig.fns.values() {
1038        let _ = writeln!(out, "  {}", canon_fn_signature(f, types));
1039    }
1040
1041    // Methods (PR #1517's own bot review, finding #2): rendered per owning
1042    // type, instance and static kept in their own sections so a rename
1043    // between the two buckets is visible too, not just a param/return change
1044    // within one.
1045    out.push_str("methods:\n");
1046    for (owner, mt) in &sig.methods {
1047        let MethodTableSignature { instance, statics } = mt;
1048        for f in instance.values() {
1049            let _ = writeln!(out, "  {owner}.{}", canon_fn_signature(f, types));
1050        }
1051        for f in statics.values() {
1052            let _ = writeln!(out, "  {owner}::{}", canon_fn_signature(f, types));
1053        }
1054    }
1055
1056    out.push_str("service_handlers:\n");
1057    for (owner, hs) in &sig.service_handlers {
1058        for h in hs {
1059            let _ = writeln!(out, "  {owner}: {}", canon_handler_signature(h, types));
1060        }
1061    }
1062
1063    out.push_str("agent_handlers:\n");
1064    for (owner, hs) in &sig.agent_handlers {
1065        for h in hs {
1066            let _ = writeln!(out, "  {owner}: {}", canon_handler_signature(h, types));
1067        }
1068    }
1069
1070    out.push_str("service_protocols:\n");
1071    for (owner, p) in &sig.service_protocols {
1072        let _ = writeln!(out, "  {owner}: {}", canon_protocol_signature(p, types));
1073    }
1074
1075    out.push_str("store:\n");
1076    for (owner, fs) in &sig.store_fields {
1077        for f in fs {
1078            let _ = writeln!(out, "  {owner}: {}", canon_store_field_signature(f, types));
1079        }
1080    }
1081
1082    out.push_str("capabilities:\n");
1083    for c in &sig.capabilities.exported {
1084        let _ = writeln!(out, "  exports {c}");
1085    }
1086    for (cap, ops) in &sig.capabilities.declared {
1087        for op in ops {
1088            let _ = writeln!(
1089                out,
1090                "  declares {cap}.{}",
1091                canon_capability_op_signature(op, types)
1092            );
1093        }
1094    }
1095    for (cap, given) in &sig.capabilities.provider_given {
1096        let mut given = given.clone();
1097        given.sort();
1098        let _ = writeln!(out, "  provides {cap} given {}", given.join(", "));
1099    }
1100    for (svc, given) in &sig.capabilities.service_given {
1101        let mut given = given.clone();
1102        given.sort();
1103        let _ = writeln!(out, "  service {svc} given {}", given.join(", "));
1104    }
1105
1106    out
1107}
1108
1109#[cfg(test)]
1110mod tests {
1111    use super::*;
1112    use bynk_syntax::ast::RefinementPred;
1113
1114    #[test]
1115    fn predicate_order_does_not_change_the_form() {
1116        // The precondition the whole increment rests on: `String where NonEmpty,
1117        // MaxLen(10)` and the same predicates reordered are the *same type*, so
1118        // they must canonicalise — and therefore hash — identically. Hashing
1119        // source order would 409 two contexts that agree perfectly.
1120        let a = Refinement {
1121            annotations: Vec::new(),
1122            predicates: vec![
1123                RefinementPred {
1124                    kind: PredKind::NonEmpty,
1125                    arg_text: None,
1126                    span: sp(),
1127                },
1128                RefinementPred {
1129                    kind: PredKind::MaxLength(10),
1130                    arg_text: None,
1131                    span: sp(),
1132                },
1133            ],
1134            span: sp(),
1135        };
1136        let b = Refinement {
1137            annotations: Vec::new(),
1138            predicates: vec![
1139                RefinementPred {
1140                    kind: PredKind::MaxLength(10),
1141                    arg_text: None,
1142                    span: sp(),
1143                },
1144                RefinementPred {
1145                    kind: PredKind::NonEmpty,
1146                    arg_text: None,
1147                    span: sp(),
1148                },
1149            ],
1150            span: sp(),
1151        };
1152        assert_eq!(canon_refinement(Some(&a)), canon_refinement(Some(&b)));
1153        assert_eq!(
1154            contract_hash(&canon_refinement(Some(&a))),
1155            contract_hash(&canon_refinement(Some(&b)))
1156        );
1157    }
1158
1159    #[test]
1160    fn a_different_predicate_set_changes_the_form() {
1161        let a = Refinement {
1162            annotations: Vec::new(),
1163            predicates: vec![RefinementPred {
1164                kind: PredKind::MaxLength(10),
1165                arg_text: None,
1166                span: sp(),
1167            }],
1168            span: sp(),
1169        };
1170        let b = Refinement {
1171            annotations: Vec::new(),
1172            predicates: vec![RefinementPred {
1173                kind: PredKind::MaxLength(11),
1174                arg_text: None,
1175                span: sp(),
1176            }],
1177            span: sp(),
1178        };
1179        assert_ne!(canon_refinement(Some(&a)), canon_refinement(Some(&b)));
1180    }
1181
1182    #[test]
1183    fn fnv1a_matches_the_published_vectors() {
1184        // FNV-1a 64-bit reference vectors. The point of hand-rolling a
1185        // *specified* hash is that two compilers agree forever; pin it.
1186        assert_eq!(contract_hash(""), "cbf29ce484222325");
1187        assert_eq!(contract_hash("a"), "af63dc4c8601ec8c");
1188        assert_eq!(contract_hash("foobar"), "85944171f73967e8");
1189    }
1190
1191    /// Build a type table by parsing a `commons`, so these tests exercise real
1192    /// declarations rather than hand-assembled AST.
1193    fn types_of(src: &str) -> HashMap<String, Arc<TypeDecl>> {
1194        let tokens = bynk_syntax::lexer::tokenize(src).expect("lex");
1195        let commons = bynk_syntax::parser::parse(&tokens, src).expect("parse");
1196        commons
1197            .items
1198            .iter()
1199            .filter_map(|i| match i {
1200                bynk_syntax::ast::CommonsItem::Type(t) => {
1201                    Some((t.name.name.clone(), Arc::new(t.clone())))
1202                }
1203                _ => None,
1204            })
1205            .collect()
1206    }
1207
1208    fn named(n: &str) -> TypeRef {
1209        TypeRef::Named(bynk_syntax::ast::Ident {
1210            name: n.to_string(),
1211            span: sp(),
1212        })
1213    }
1214
1215    fn svc(param_ty: TypeRef) -> CrossContextService {
1216        CrossContextService {
1217            name: "probe".to_string(),
1218            params: vec![("p".to_string(), param_ty)],
1219            return_type: TypeRef::Base(bynk_syntax::ast::BaseType::String, sp()),
1220            span: sp(),
1221            foreign_callers: Vec::new(),
1222        }
1223    }
1224
1225    /// A record's **field order** is not wire-observable — a JSON object is
1226    /// unordered — so it must not move the hash. This is the false-positive side,
1227    /// and it is the one that matters most: a spurious 409 breaks a working
1228    /// deployment.
1229    #[test]
1230    fn record_field_order_does_not_change_the_hash() {
1231        let a = types_of("commons x\n\ntype P = { one: Int, two: String }\n");
1232        let b = types_of("commons x\n\ntype P = { two: String, one: Int }\n");
1233        assert_eq!(
1234            service_contract_hash(&svc(named("P")), &a),
1235            service_contract_hash(&svc(named("P")), &b),
1236        );
1237    }
1238
1239    /// Field **presence** and **type**, by contrast, are exactly what the hash
1240    /// exists to pin. These are the cases a co-compiled build rejects
1241    /// structurally — but a skewed *deploy* cannot, which is why the hash carries
1242    /// them.
1243    #[test]
1244    fn field_presence_name_and_type_change_the_hash() {
1245        let base = types_of("commons x\n\ntype P = { one: Int, two: String }\n");
1246        let h = service_contract_hash(&svc(named("P")), &base);
1247
1248        let renamed = types_of("commons x\n\ntype P = { one: Int, three: String }\n");
1249        assert_ne!(
1250            h,
1251            service_contract_hash(&svc(named("P")), &renamed),
1252            "rename"
1253        );
1254
1255        let dropped = types_of("commons x\n\ntype P = { two: String }\n");
1256        assert_ne!(h, service_contract_hash(&svc(named("P")), &dropped), "drop");
1257
1258        let retyped = types_of("commons x\n\ntype P = { one: String, two: String }\n");
1259        assert_ne!(
1260            h,
1261            service_contract_hash(&svc(named("P")), &retyped),
1262            "retype"
1263        );
1264    }
1265
1266    /// #1969: an inline field refinement is part of the field's type, and the
1267    /// decoder checks it, so adding, changing or dropping one changes the
1268    /// hash. Its predicates canonicalise as a set, like a named refined type's.
1269    #[test]
1270    fn an_inline_field_refinement_changes_the_hash_as_a_set() {
1271        let plain = types_of("commons x\n\ntype P = { qty: Int }\n");
1272        let refined = types_of("commons x\n\ntype P = { qty: Int where Positive }\n");
1273        let both =
1274            types_of("commons x\n\ntype P = { name: String where NonEmpty && MaxLength(4) }\n");
1275        let swapped =
1276            types_of("commons x\n\ntype P = { name: String where MaxLength(4) && NonEmpty }\n");
1277        assert_ne!(
1278            service_contract_hash(&svc(named("P")), &plain),
1279            service_contract_hash(&svc(named("P")), &refined),
1280        );
1281        assert_eq!(
1282            service_normal_form(&svc(named("P")), &refined),
1283            "probe(p: P{qty: Int where Positive}) -> String"
1284        );
1285        assert_eq!(
1286            service_contract_hash(&svc(named("P")), &both),
1287            service_contract_hash(&svc(named("P")), &swapped),
1288        );
1289    }
1290
1291    /// A sum's **variant order** is invisible to the wire (the payload carries a
1292    /// `kind` discriminant); its variant *set* is not.
1293    #[test]
1294    fn sum_variant_order_does_not_change_the_hash_but_the_set_does() {
1295        let a = types_of("commons x\n\ntype E = enum { Alpha, Beta }\n");
1296        let b = types_of("commons x\n\ntype E = enum { Beta, Alpha }\n");
1297        assert_eq!(
1298            service_contract_hash(&svc(named("E")), &a),
1299            service_contract_hash(&svc(named("E")), &b),
1300        );
1301        let c = types_of("commons x\n\ntype E = enum { Alpha, Gamma }\n");
1302        assert_ne!(
1303            service_contract_hash(&svc(named("E")), &a),
1304            service_contract_hash(&svc(named("E")), &c),
1305        );
1306    }
1307
1308    /// An **opaque** type's predicate is excluded: the consumer cannot see it by
1309    /// construction, so no consumer behaviour can depend on it, and including it
1310    /// would manufacture skew between two contexts that cannot disagree. Its
1311    /// *representation* is still part of the contract.
1312    #[test]
1313    fn an_opaque_types_predicate_is_excluded_but_its_representation_is_not() {
1314        let loose = types_of("commons x\n\ntype Id = opaque String where NonEmpty\n");
1315        let tight = types_of("commons x\n\ntype Id = opaque String where MaxLength(4)\n");
1316        assert_eq!(
1317            service_contract_hash(&svc(named("Id")), &loose),
1318            service_contract_hash(&svc(named("Id")), &tight),
1319            "tightening an opaque predicate must not 409 a caller that cannot see it"
1320        );
1321
1322        // A *transparent* refined type is the opposite: the consumer can see the
1323        // predicate, so it is part of the contract.
1324        let ra = types_of("commons x\n\ntype C = String where MaxLength(4)\n");
1325        let rb = types_of("commons x\n\ntype C = String where MaxLength(5)\n");
1326        assert_ne!(
1327            service_contract_hash(&svc(named("C")), &ra),
1328            service_contract_hash(&svc(named("C")), &rb),
1329        );
1330    }
1331
1332    /// `NonEmpty` is sugar for `MinLength(1)` (R12.2, T1.8, Decision A) —
1333    /// pinned directly against the canonicaliser so a future edit to this arm
1334    /// is a deliberate, visible change rather than a silent regression.
1335    #[test]
1336    fn non_empty_canonicalises_to_min_length_one() {
1337        assert_eq!(canon_predicate(&PredKind::NonEmpty), "MinLength(1)");
1338    }
1339
1340    /// The counterpart to `non_empty_canonicalises_to_min_length_one`: the
1341    /// `Positive`/`NonNegative` → `InRange` fold is **declined** (#1049) —
1342    /// neither base has a writable bound standing for `∞`. Pinned so
1343    /// reversing that decision trips a named test rather than a fixture
1344    /// hash.
1345    #[test]
1346    fn positive_and_non_negative_stay_their_own_canonical_literals() {
1347        assert_eq!(canon_predicate(&PredKind::Positive), "Positive");
1348        assert_eq!(canon_predicate(&PredKind::NonNegative), "NonNegative");
1349    }
1350
1351    /// The consequence that matters: two boundary types spelling the same
1352    /// refinement differently must hash identically, or two contexts that
1353    /// agree perfectly 409 each other.
1354    #[test]
1355    fn non_empty_and_min_length_one_hash_identically() {
1356        let a = types_of("commons x\n\ntype C = String where NonEmpty\n");
1357        let b = types_of("commons x\n\ntype C = String where MinLength(1)\n");
1358        assert_eq!(
1359            service_contract_hash(&svc(named("C")), &a),
1360            service_contract_hash(&svc(named("C")), &b),
1361            "NonEmpty and MinLength(1) are the same refinement and must hash the same"
1362        );
1363    }
1364
1365    /// After the fold, `NonEmpty` and `MinLength(1)` are the same canonical
1366    /// string, so a redundant `NonEmpty && MinLength(1)` conjunction must dedup
1367    /// to one entry, not two — the same idempotence `canon_refinement`'s sort+
1368    /// dedup already promises for any other repeated predicate.
1369    #[test]
1370    fn non_empty_and_min_length_one_together_dedup_to_one_entry() {
1371        let r = Refinement {
1372            annotations: Vec::new(),
1373            predicates: vec![
1374                RefinementPred {
1375                    kind: PredKind::NonEmpty,
1376                    arg_text: None,
1377                    span: sp(),
1378                },
1379                RefinementPred {
1380                    kind: PredKind::MinLength(1),
1381                    arg_text: None,
1382                    span: sp(),
1383                },
1384            ],
1385            span: sp(),
1386        };
1387        assert_eq!(canon_refinement(Some(&r)), "where MinLength(1)");
1388    }
1389
1390    /// A recursive record is a legal contract (its codec terminates on the data),
1391    /// but its expansion is not — the walk must terminate rather than blow the
1392    /// stack, and two different recursive shapes must still differ.
1393    #[test]
1394    fn a_recursive_record_terminates_and_stays_distinguishable() {
1395        let a = types_of("commons x\n\ntype Node = { v: Int, next: Option[Node] }\n");
1396        let b = types_of("commons x\n\ntype Node = { v: String, next: Option[Node] }\n");
1397        let ha = service_contract_hash(&svc(named("Node")), &a);
1398        assert_ne!(ha, service_contract_hash(&svc(named("Node")), &b));
1399    }
1400
1401    /// State-migrations S0 (#2204): the storage renderings are structural —
1402    /// stored bytes carry no type names — and recursion still terminates,
1403    /// with the back-reference as the only name left.
1404    #[test]
1405    fn storage_renderings_drop_type_names_and_terminate_on_recursion() {
1406        let t =
1407            types_of("commons x\n\ntype Node = { v: Int where NonNegative, next: Option[Node] }\n");
1408        let (structure, full) = canon_storage_type(&named("Node"), &t);
1409        assert_eq!(structure, "{next: Option[@1], v: Int}");
1410        assert_eq!(full, "{next: Option[@1], v: Int where NonNegative}");
1411
1412        let renamed =
1413            types_of("commons x\n\ntype Link = { v: Int where NonNegative, next: Option[Link] }\n");
1414        let (renamed_structure, _) = canon_storage_type(&named("Link"), &renamed);
1415        assert_eq!(
1416            renamed_structure, structure,
1417            "renaming a recursive type changes nothing on disk (#2204 review)"
1418        );
1419
1420        // The positional anchor still tells different cycles apart: here the
1421        // inner type points back to the *outer* one, two levels out.
1422        let mutual =
1423            types_of("commons x\n\ntype A = { b: Option[B] }\ntype B = { a: Option[A], v: Int }\n");
1424        let selfish =
1425            types_of("commons x\n\ntype A = { b: Option[B] }\ntype B = { a: Option[B], v: Int }\n");
1426        assert_eq!(
1427            canon_storage_type(&named("A"), &mutual).0,
1428            "{b: Option[{a: Option[@2], v: Int}]}"
1429        );
1430        assert_ne!(
1431            canon_storage_type(&named("A"), &mutual),
1432            canon_storage_type(&named("A"), &selfish)
1433        );
1434
1435        let flat_a = types_of("commons x\n\ntype A = { title: String }\n");
1436        let flat_b = types_of("commons x\n\ntype B = { title: String }\n");
1437        assert_eq!(
1438            canon_storage_type(&named("A"), &flat_a),
1439            canon_storage_type(&named("B"), &flat_b),
1440            "renaming a non-recursive type changes nothing on disk"
1441        );
1442
1443        // Nor does renaming a refined type, or one used as a map key or as a
1444        // sum variant's payload: no position in the walk is nominal.
1445        let qty = types_of("commons x\n\ntype Qty = Int where NonNegative\n");
1446        let count = types_of("commons x\n\ntype Count = Int where NonNegative\n");
1447        assert_eq!(
1448            canon_storage_type(&named("Qty"), &qty),
1449            canon_storage_type(&named("Count"), &count),
1450        );
1451        let map = |key: &str| TypeRef::Map(Box::new(named(key)), Box::new(named(key)), sp());
1452        assert_eq!(
1453            canon_storage_type(&map("Qty"), &qty),
1454            canon_storage_type(&map("Count"), &count),
1455        );
1456        let sum_a = types_of("commons x\n\ntype P = { n: Int }\ntype S = | One(p: P) | Two\n");
1457        let sum_b = types_of("commons x\n\ntype Q = { n: Int }\ntype S = | One(p: Q) | Two\n");
1458        assert_eq!(
1459            canon_storage_type(&named("S"), &sum_a),
1460            canon_storage_type(&named("S"), &sum_b),
1461        );
1462    }
1463
1464    /// Stored sum payloads are keyed by field name (`payload_prop`), so in
1465    /// storage a payload renders like a record: renaming a payload field is a
1466    /// change, reordering payload fields is not (#2204 review).
1467    #[test]
1468    fn storage_renderings_name_and_sort_sum_payload_fields() {
1469        let base = types_of("commons x\n\ntype S = | One(a: Int, b: String) | Two\n");
1470        let renamed = types_of("commons x\n\ntype S = | One(c: Int, b: String) | Two\n");
1471        let reordered = types_of("commons x\n\ntype S = | One(b: String, a: Int) | Two\n");
1472        let (structure, _) = canon_storage_type(&named("S"), &base);
1473        assert_eq!(structure, "|One(a: Int, b: String)|Two");
1474        assert_ne!(
1475            canon_storage_type(&named("S"), &base),
1476            canon_storage_type(&named("S"), &renamed)
1477        );
1478        assert_eq!(
1479            canon_storage_type(&named("S"), &base),
1480            canon_storage_type(&named("S"), &reordered)
1481        );
1482        // The contract form agrees: payloads are keyed by name on the wire, so
1483        // a rename is a break and a reorder is not.
1484        assert_ne!(
1485            service_contract_hash(&svc(named("S")), &base),
1486            service_contract_hash(&svc(named("S")), &renamed)
1487        );
1488        assert_eq!(
1489            service_contract_hash(&svc(named("S")), &base),
1490            service_contract_hash(&svc(named("S")), &reordered)
1491        );
1492        assert_eq!(
1493            service_normal_form(&svc(named("S")), &base),
1494            "probe(p: S|One(a: Int, b: String)|Two) -> String"
1495        );
1496    }
1497
1498    /// The stored owner re-validates its opaque values, so the full storage
1499    /// rendering keeps an opaque predicate the contract form elides — and the
1500    /// contract hash itself is unchanged by the new modes.
1501    #[test]
1502    fn storage_full_rendering_keeps_an_opaque_predicate_the_contract_elides() {
1503        let a = types_of("commons x\n\ntype Code = opaque String where MaxLength(10)\n");
1504        let b = types_of("commons x\n\ntype Code = opaque String where MaxLength(5)\n");
1505        let (sa, fa) = canon_storage_type(&named("Code"), &a);
1506        let (sb, fb) = canon_storage_type(&named("Code"), &b);
1507        assert_eq!(sa, "String");
1508        assert_eq!(sa, sb, "the structure ignores the predicate");
1509        assert_ne!(fa, fb, "the full form sees the tightened predicate");
1510        assert_eq!(
1511            service_contract_hash(&svc(named("Code")), &a),
1512            service_contract_hash(&svc(named("Code")), &b),
1513            "the contract still elides an opaque predicate"
1514        );
1515    }
1516
1517    /// A generic type's **parameter name** is not wire-observable: `Page[T]` and
1518    /// the same declaration spelled with `U` are the same type with the same
1519    /// shape. Renaming one is a refactor, and must not 409 a caller.
1520    ///
1521    /// Caught in review of #658: the body used to expand with the parameter
1522    /// *unsubstituted*, so the name leaked into the form. Same class as record
1523    /// field order and predicate order — the false-positive side the module's
1524    /// standard exists to protect.
1525    #[test]
1526    fn a_generic_type_parameter_rename_does_not_change_the_hash() {
1527        let t = types_of(
1528            "commons x\n\ntype Order = { id: Int }\ntype Page[T] = { items: List[T], total: Int }\n",
1529        );
1530        let u = types_of(
1531            "commons x\n\ntype Order = { id: Int }\ntype Page[U] = { items: List[U], total: Int }\n",
1532        );
1533        let app = TypeRef::App {
1534            name: bynk_syntax::ast::Ident {
1535                name: "Page".to_string(),
1536                span: sp(),
1537            },
1538            args: vec![named("Order")],
1539            span: sp(),
1540        };
1541        assert_eq!(
1542            service_contract_hash(&svc(app.clone()), &t),
1543            service_contract_hash(&svc(app), &u),
1544            "renaming a generic type parameter must not change the contract hash"
1545        );
1546    }
1547
1548    /// The converse: the *argument* a generic is instantiated at is entirely
1549    /// wire-observable, so it must still move the hash.
1550    #[test]
1551    fn a_generic_argument_change_does_change_the_hash() {
1552        let t = types_of(
1553            "commons x\n\ntype Order = { id: Int }\ntype Other = { id: String }\ntype Page[T] = { items: List[T] }\n",
1554        );
1555        let app = |arg: &str| TypeRef::App {
1556            name: bynk_syntax::ast::Ident {
1557                name: "Page".to_string(),
1558                span: sp(),
1559            },
1560            args: vec![named(arg)],
1561            span: sp(),
1562        };
1563        assert_ne!(
1564            service_contract_hash(&svc(app("Order")), &t),
1565            service_contract_hash(&svc(app("Other")), &t),
1566        );
1567    }
1568
1569    /// And the parameter is genuinely *substituted*, not merely ignored: the form
1570    /// shows the instantiated shape rather than a dangling `T`.
1571    #[test]
1572    fn a_generic_body_expands_over_its_concrete_argument() {
1573        let t = types_of("commons x\n\ntype Page[T] = { items: List[T] }\n");
1574        let app = TypeRef::App {
1575            name: bynk_syntax::ast::Ident {
1576                name: "Page".to_string(),
1577                span: sp(),
1578            },
1579            args: vec![TypeRef::Base(bynk_syntax::ast::BaseType::Int, sp())],
1580            span: sp(),
1581        };
1582        let nf = service_normal_form(&svc(app), &t);
1583        assert!(nf.contains("List[Int]"), "{nf}");
1584        assert!(
1585            !nf.contains("List[T]"),
1586            "the parameter must not survive: {nf}"
1587        );
1588    }
1589
1590    fn route(types_src: &str) -> (HttpRouteContract, HashMap<String, Arc<TypeDecl>>) {
1591        let t = types_of(types_src);
1592        let named = |n: &str| {
1593            TypeRef::Named(bynk_syntax::ast::Ident {
1594                name: n.to_string(),
1595                span: sp(),
1596            })
1597        };
1598        (
1599            HttpRouteContract {
1600                method: "POST".to_string(),
1601                path: "/orders".to_string(),
1602                params: vec![HttpRouteParam {
1603                    kind: "body-json".to_string(),
1604                    name: "body".to_string(),
1605                    ty: Some(named("Order")),
1606                    detail: None,
1607                }],
1608                success: Some(named("Order")),
1609                replies: vec![
1610                    (201, "Created".to_string(), "Value".to_string()),
1611                    (
1612                        400,
1613                        "StructuralMismatch".to_string(),
1614                        "BoundaryError".to_string(),
1615                    ),
1616                ],
1617            },
1618            t,
1619        )
1620    }
1621
1622    /// The hash moves when what a client acts on moves, and only then.
1623    #[test]
1624    fn an_http_route_hash_follows_what_a_client_acts_on() {
1625        let base = "commons x\n\ntype Order = { sku: String, qty: Int }\n";
1626        let (r, t) = route(base);
1627        let h = http_route_contract_hash(&r, &t);
1628        assert_eq!(h.len(), 16);
1629        // Pinned absolutely: a change to `canon_type` or to this form moves every route's
1630        // hash, and a generated client carries it, so that is a decision, not a side effect.
1631        assert_eq!(
1632            http_route_normal_form(&r, &t),
1633            "POST /orders | body-json body: Order{qty: Int, sku: String} | ok: Order{qty: Int, sku: String} | replies: 201:Created:Value,400:StructuralMismatch:BoundaryError"
1634        );
1635        assert_eq!(h, "0f4346f8f1c4f893");
1636        // Field order, replies order and a repeated reply are not contract changes.
1637        let (_, reordered) = route("commons x\n\ntype Order = { qty: Int, sku: String }\n");
1638        assert_eq!(h, http_route_contract_hash(&r, &reordered));
1639        let mut shuffled = r.clone();
1640        shuffled.replies.reverse();
1641        shuffled
1642            .replies
1643            .push((201, "Created".to_string(), "Value".to_string()));
1644        assert_eq!(h, http_route_contract_hash(&shuffled, &t));
1645        // A field, a refinement, a status, a method, a path and a body kind are.
1646        let (_, wider) =
1647            route("commons x\n\ntype Order = { sku: String, qty: Int, note: Option[String] }\n");
1648        assert_ne!(h, http_route_contract_hash(&r, &wider));
1649        let (_, refined) =
1650            route("commons x\n\ntype Order = { sku: String, qty: Int where InRange(1, 9) }\n");
1651        assert_ne!(h, http_route_contract_hash(&r, &refined));
1652        let mut other = r.clone();
1653        other
1654            .replies
1655            .push((409, "Conflict".to_string(), "Message".to_string()));
1656        assert_ne!(h, http_route_contract_hash(&other, &t));
1657        let mut other = r.clone();
1658        other.method = "PUT".to_string();
1659        assert_ne!(h, http_route_contract_hash(&other, &t));
1660        let mut other = r.clone();
1661        other.path = "/orders/:id".to_string();
1662        assert_ne!(h, http_route_contract_hash(&other, &t));
1663        let mut other = r.clone();
1664        other.params[0].kind = "body-form".to_string();
1665        assert_ne!(h, http_route_contract_hash(&other, &t));
1666    }
1667
1668    /// A service hash does not depend on the order its routes are declared in.
1669    #[test]
1670    fn an_http_service_hash_is_independent_of_route_order() {
1671        let a = vec!["aaaa".to_string(), "bbbb".to_string()];
1672        let b = vec!["bbbb".to_string(), "aaaa".to_string()];
1673        assert_eq!(
1674            http_service_contract_hash(&a),
1675            http_service_contract_hash(&b)
1676        );
1677        assert_ne!(
1678            http_service_contract_hash(&a),
1679            http_service_contract_hash(&["aaaa".to_string()])
1680        );
1681    }
1682
1683    fn sp() -> bynk_syntax::span::Span {
1684        bynk_syntax::span::Span::new(0, 0)
1685    }
1686}