Skip to main content

cbcl_core/
r7.rs

1//! R7 (SPEC-019): installation checks for the `(state …)` clause, the
2//! compiler-inserted `:replaces` field, self-addressed naming, and the
3//! message-level state-shape check (R.4).
4
5#![forbid(unsafe_code)]
6
7use crate::dialect::Dialect;
8use crate::message::Message;
9use crate::sexpr::{Atom, SExpr};
10use crate::shape::{ShapeConstraint, ShapeRule, ShapeViolation, TypeConstraint};
11use crate::state::{
12    field_type, keyword_fields, opener_verb, Rule, StateBounds, StateClause, RESERVED_REPLACES,
13    ROUTING_KEYWORDS,
14};
15use alloc::collections::BTreeSet;
16use alloc::format;
17use alloc::string::{String, ToString};
18use alloc::vec::Vec;
19use core::fmt;
20
21/// The prefix of a self-addressed dialect name (SPEC-019 R.6): the same
22/// spelling as every content address on the wire.
23pub const SELF_ADDRESS_PREFIX: &str = crate::multihash::TEXT_PREFIX;
24
25/// An R7 installation violation (SPEC-019 CON-1905).
26#[derive(Debug, Clone, PartialEq, Eq)]
27#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
28pub enum R7Violation {
29    Malformed(String),
30    UnknownVerb(String),
31    UnknownField {
32        verb: String,
33        field: String,
34    },
35    Typing(String),
36    Replaces(String),
37    Domain(String),
38    Bounds(String),
39    Name {
40        expected: String,
41        found: String,
42    },
43    /// A threshold read not admitted by its field's carrier, or a set that
44    /// is not pairwise incompatible (SPEC-038 REQ-3802, CON-3801).
45    Threshold(String),
46}
47
48impl fmt::Display for R7Violation {
49    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
50        match self {
51            R7Violation::Malformed(s) => write!(f, "malformed state clause: {s}"),
52            R7Violation::UnknownVerb(v) => {
53                write!(f, "state clause names undefined performative '{v}'")
54            }
55            R7Violation::UnknownField { verb, field } => {
56                write!(
57                    f,
58                    "state clause names field :{field} not required by the shape of '{verb}'"
59                )
60            }
61            R7Violation::Typing(s) => write!(f, "state clause typing: {s}"),
62            R7Violation::Replaces(s) => write!(f, ":replaces: {s}"),
63            R7Violation::Domain(s) => write!(f, "domain: {s}"),
64            R7Violation::Bounds(s) => write!(f, "state bounds: {s}"),
65            R7Violation::Threshold(s) => write!(f, "threshold {s}"),
66            R7Violation::Name { expected, found } => {
67                write!(
68                    f,
69                    "self-addressed dialect must be named '{expected}', found '{found}'"
70                )
71            }
72        }
73    }
74}
75
76/// The dialect's bounds, defaults when the clause is absent.
77pub fn bounds_of(d: &Dialect) -> StateBounds {
78    d.state_bounds.clone().unwrap_or_default()
79}
80
81/// Whether a verb's shape declares `:replaces` at the top level.
82fn shape_has_replaces(shapes: &[ShapeConstraint], verb: &str) -> bool {
83    field_type(shapes, verb, RESERVED_REPLACES).is_some()
84        || shapes.iter().filter(|s| s.performative == verb).any(|s| {
85            s.rules.iter().any(|r| matches!(r,
86                ShapeRule::Require { keyword, .. } | ShapeRule::Optional { keyword, .. } if keyword == RESERVED_REPLACES))
87        })
88}
89
90/// Insert `(require :replaces list)` into the shape of every verb the
91/// clause names as a register writer, signer writer, delete, or remove verb
92/// (ADR-1901, REQ-1934). Called by
93/// the parser after all clauses are read. Idempotent.
94pub fn insert_replaces(d: &mut Dialect) {
95    let Some(clause) = d.state.as_ref() else {
96        return;
97    };
98    let verbs: Vec<String> = clause
99        .replaces_verbs()
100        .into_iter()
101        .map(String::from)
102        .collect();
103    let escrow_verbs: Vec<String> = clause
104        .fields()
105        .filter_map(|(_, r)| {
106            if let Rule::BoundedCounter(c) = r {
107                Some(
108                    c.operation_verbs()
109                        .into_iter()
110                        .map(String::from)
111                        .collect::<Vec<_>>(),
112                )
113            } else {
114                None
115            }
116        })
117        .flatten()
118        .collect();
119    for verb in escrow_verbs {
120        for (keyword, ty) in [
121            (crate::escrow::PREV, TypeConstraint::Symbol),
122            (crate::escrow::DEPS, TypeConstraint::List),
123        ] {
124            if field_type(&d.shapes, &verb, keyword).is_some() {
125                continue;
126            }
127            let rule = ShapeRule::Require {
128                keyword: keyword.into(),
129                type_constraint: Some(ty),
130                children: Vec::new(),
131            };
132            match d.shapes.iter_mut().find(|s| s.performative == verb) {
133                Some(s) => s.rules.push(rule),
134                None => d.shapes.push(ShapeConstraint {
135                    performative: verb.clone(),
136                    rules: alloc::vec![rule],
137                }),
138            }
139        }
140    }
141    let quorum_verbs: Vec<String> = clause
142        .fields()
143        .filter_map(|(_, r)| match r {
144            Rule::BoundedCounter(c) if c.certification.is_quorum() => Some(
145                c.operation_verbs()
146                    .into_iter()
147                    .map(String::from)
148                    .collect::<Vec<_>>(),
149            ),
150            _ => None,
151        })
152        .flatten()
153        .collect();
154    for verb in quorum_verbs {
155        let rule = ShapeRule::Require {
156            keyword: crate::escrow::NONCE.into(),
157            type_constraint: Some(TypeConstraint::String),
158            children: Vec::new(),
159        };
160        if field_type(&d.shapes, &verb, crate::escrow::NONCE).is_none() {
161            match d.shapes.iter_mut().find(|s| s.performative == verb) {
162                Some(s) => s.rules.push(rule),
163                None => d.shapes.push(ShapeConstraint {
164                    performative: verb,
165                    rules: alloc::vec![rule],
166                }),
167            }
168        }
169    }
170    for verb in verbs {
171        if shape_has_replaces(&d.shapes, &verb) {
172            continue;
173        }
174        let rule = ShapeRule::Require {
175            keyword: String::from(RESERVED_REPLACES),
176            type_constraint: Some(TypeConstraint::List),
177            children: Vec::new(),
178        };
179        match d.shapes.iter_mut().find(|s| s.performative == verb) {
180            Some(shape) => shape.rules.push(rule),
181            None => d.shapes.push(ShapeConstraint {
182                performative: verb,
183                rules: alloc::vec![rule],
184            }),
185        }
186    }
187}
188
189/// The keywords a verb's shape declares at the top level.
190pub fn declared_keywords(shapes: &[ShapeConstraint], verb: &str) -> BTreeSet<String> {
191    let mut out = BTreeSet::new();
192    for shape in shapes.iter().filter(|s| s.performative == verb) {
193        for rule in &shape.rules {
194            if let ShapeRule::Require { keyword, .. } | ShapeRule::Optional { keyword, .. } = rule {
195                out.insert(keyword.clone());
196            }
197        }
198    }
199    out
200}
201
202fn is_scalar(tc: &TypeConstraint) -> bool {
203    if let TypeConstraint::Contract(c) = tc {
204        return c.representations() != 0 && c.representations() & !(1 | 2 | 4 | 8 | 16) == 0;
205    }
206    matches!(
207        tc,
208        TypeConstraint::String
209            | TypeConstraint::Hlc
210            | TypeConstraint::Integer
211            | TypeConstraint::Number
212            | TypeConstraint::Float
213            | TypeConstraint::Decimal
214            | TypeConstraint::Nonnegative
215            | TypeConstraint::Bool
216    )
217}
218
219/// R7 installation checks (SPEC-019 REQ-1904–1910, 1927). Empty for a
220/// dialect with neither clause (REQ-1909).
221pub fn r7_violations(d: &Dialect) -> Vec<R7Violation> {
222    let mut out: Vec<R7Violation> = crate::escrow::declaration_errors(d)
223        .into_iter()
224        .map(R7Violation::Typing)
225        .collect();
226    let bounds = bounds_of(d);
227    let defaults = StateBounds::default();
228    if let Some(b) = &d.state_bounds {
229        if b.max_string > defaults.max_string
230            || b.max_list > defaults.max_list
231            || b.max_number > defaults.max_number
232            || b.max_fields > defaults.max_fields
233        {
234            out.push(R7Violation::Bounds(String::from(
235                "a bound may not exceed its default",
236            )));
237        }
238        if b.max_string == 0 || b.max_list == 0 || b.max_number <= 0 || b.max_fields == 0 {
239            out.push(R7Violation::Bounds(String::from(
240                "a bound must be positive",
241            )));
242        }
243    }
244    let Some(clause) = d.state.as_ref() else {
245        if d.name.starts_with(SELF_ADDRESS_PREFIX) {
246            check_name(d, &mut out);
247        }
248        return out;
249    };
250
251    // REQ-1904: at most max-fields fields; a threshold renders as a field
252    // (SPEC-038 CON-3801) and counts as one.
253    let field_count = clause.fields().count()
254        + clause.thresholds().count()
255        + clause
256            .entries
257            .iter()
258            .filter(|entry| matches!(entry, crate::state::Entry::Condition { .. }))
259            .count();
260    if field_count == 0 {
261        out.push(R7Violation::Malformed(String::from(
262            "a state clause declares at least one field",
263        )));
264    }
265    if field_count as u32 > bounds.max_fields {
266        out.push(R7Violation::Bounds(format!(
267            "{field_count} fields exceed max-fields {}",
268            bounds.max_fields
269        )));
270    }
271    let mut names: BTreeSet<&str> = BTreeSet::new();
272    for (name, _) in clause.fields() {
273        if !names.insert(name) {
274            out.push(R7Violation::Malformed(format!("duplicate field '{name}'")));
275        }
276    }
277    for definition in clause.lattices() {
278        if !names.insert(&definition.name) {
279            out.push(R7Violation::Malformed(format!(
280                "duplicate lattice/field name '{}'",
281                definition.name
282            )));
283        }
284        if let Err(reason) = definition.validate(bounds.max_list as usize) {
285            out.push(R7Violation::Typing(format!(
286                "lattice '{}': {reason}",
287                definition.name
288            )));
289        }
290    }
291    for (field, rule) in clause.fields() {
292        if let Rule::Lift(lift) = rule {
293            match &lift.table {
294                None => out.push(R7Violation::Typing(format!(
295                    "field '{field}' references undefined or invalid lattice '{}'",
296                    lift.lattice
297                ))),
298                Some(table) => {
299                    if let Err(reason) = lift.validate(table) {
300                        out.push(R7Violation::Typing(format!("lift '{field}': {reason}")));
301                    }
302                }
303            }
304        }
305    }
306    for (field, rule) in clause.fields() {
307        if let Rule::Context { path, definition } = rule {
308            if !definition.as_ref().is_some_and(|d| d.valid_path(path)) {
309                out.push(R7Violation::Typing(format!(
310                    "context '{field}' names an unknown path or role"
311                )));
312            }
313        }
314    }
315    check_thresholds(d, clause, &mut names, &mut out);
316    let mut frozen_fields = BTreeSet::new();
317    for (field, verb, _) in clause.freezes() {
318        if clause.rule_of(field).is_none() || !frozen_fields.insert(field) {
319            out.push(R7Violation::Malformed(format!(
320                "freeze field '{field}' is undefined or has multiple freeze declarations"
321            )));
322        }
323        if !d
324            .performatives
325            .iter()
326            .any(|p| p.name == verb && p.role.as_ref().is_some_and(|r| !r.from.is_empty()))
327        {
328            out.push(R7Violation::Malformed(format!(
329                "freeze verb '{verb}' must be defined with a :from role"
330            )));
331        }
332    }
333
334    // REQ-1905: protocol with exactly one opener.
335    let opener = match d.causal_protocol.as_ref() {
336        None => {
337            out.push(R7Violation::Malformed(String::from(
338                "a state clause requires a protocol clause",
339            )));
340            None
341        }
342        Some(p) => {
343            let o = opener_verb(p);
344            if o.is_none() {
345                out.push(R7Violation::Malformed(String::from(
346                    "the protocol must have exactly one performative whose only predecessor is begin",
347                )));
348            }
349            o.map(String::from)
350        }
351    };
352
353    // REQ-1905: references resolve; REQ-1906: typing.
354    let defined = |verb: &str| d.performatives.iter().any(|p| p.name == verb);
355    for verb in clause.state_bearing_verbs() {
356        if !defined(verb) {
357            out.push(R7Violation::UnknownVerb(String::from(verb)));
358        }
359    }
360    let ty = |verb: &str, key: &str| field_type(&d.shapes, verb, key);
361    for (verb, key) in clause.data_fields() {
362        if key == RESERVED_REPLACES {
363            out.push(R7Violation::Replaces(format!(
364                "'{verb}' reads :replaces as data"
365            )));
366            continue;
367        }
368        match ty(verb, key) {
369            None => {
370                if defined(verb) {
371                    out.push(R7Violation::UnknownField {
372                        verb: String::from(verb),
373                        field: String::from(key),
374                    });
375                }
376            }
377            Some(TypeConstraint::Symbol) if crate::escrow::recipient_field(d, verb, key) => {}
378            Some(TypeConstraint::Symbol) | Some(TypeConstraint::Keyword) => {
379                out.push(R7Violation::Typing(format!(
380                    "field :{key} of '{verb}' is a symbol or keyword; state-bearing fields are string, number, bool, or list"
381                )));
382            }
383            Some(TypeConstraint::Contract(c)) if c.representations() & (32 | 64) != 0 => {
384                out.push(R7Violation::Typing(format!(
385                    "field :{key} of '{verb}' contract admits symbols or keywords"
386                )));
387            }
388            Some(_) => {}
389        }
390    }
391    let field_types: Vec<(String, &Rule)> =
392        clause.fields().map(|(n, r)| (String::from(n), r)).collect();
393    for (name, rule) in &field_types {
394        if let Some((verb, clock)) = rule.clock_field() {
395            if ty(verb, clock) != Some(TypeConstraint::Hlc) || !d.shapes.iter().filter(|s| s.performative == verb).any(|s| s.rules.iter().any(|r| matches!(r, ShapeRule::Require { keyword, type_constraint: Some(tc), .. } if keyword == clock && tc.representation() == Some(TypeConstraint::Hlc)))) {
396                out.push(R7Violation::Typing(format!("LWW clock :{clock} of '{verb}' must be a required hlc field")));
397            }
398            if bounds.max_string < crate::hlc::WIRE_LEN as u32 {
399                out.push(R7Violation::Bounds(
400                    "max-string cannot hold a canonical HLC".into(),
401                ));
402            }
403            let conflicts = match rule {
404                Rule::LwwRegister { key, .. } | Rule::LwwPerSigner { key, .. } => clock == key,
405                Rule::LwwMap { key, value, .. } => clock == key || clock == value,
406                _ => false,
407            };
408            if conflicts
409                || ROUTING_KEYWORDS.contains(&clock)
410                || [
411                    RESERVED_REPLACES,
412                    crate::escrow::PREV,
413                    crate::escrow::DEPS,
414                    crate::escrow::NONCE,
415                ]
416                .contains(&clock)
417            {
418                out.push(R7Violation::Typing(
419                    "LWW clock must be a distinct application field".into(),
420                ));
421            }
422        }
423        match rule {
424            Rule::Progress { verb } => {
425                if let Some(protocol) = &d.causal_protocol {
426                    if let Err(reason) = crate::repeat::position_chain(protocol, verb) {
427                        out.push(R7Violation::Typing(reason));
428                    }
429                }
430            }
431            Rule::LwwMap { verb, key, .. } | Rule::ValuesPerKey { verb, key, .. } => {
432                if let Some(tc) = ty(verb, key) {
433                    if !is_scalar(&tc) {
434                        out.push(R7Violation::Typing(format!(
435                            "map key :{key} of '{verb}' must be scalar (field '{name}')"
436                        )));
437                    }
438                }
439            }
440            Rule::SetUnion { verb, key } | Rule::ObservedSet { add: verb, key, .. } => {
441                if let Some(tc) = ty(verb, key) {
442                    if !is_scalar(&tc) {
443                        out.push(R7Violation::Typing(format!(
444                            "value :{key} of '{verb}' must be scalar (field '{name}')"
445                        )));
446                    }
447                }
448            }
449            Rule::Counter { inc, dec, key } => {
450                if inc == dec {
451                    out.push(R7Violation::Typing(format!(
452                        "counter '{name}' names the same verb twice"
453                    )));
454                }
455                for v in [inc, dec] {
456                    if let Some(tc) = ty(v, key) {
457                        if !matches!(tc, TypeConstraint::Integer | TypeConstraint::Nonnegative) {
458                            out.push(R7Violation::Typing(format!(
459                                "counter '{name}': :{key} of '{v}' must be an integer"
460                            )));
461                        }
462                    }
463                }
464            }
465            Rule::Histogram { field } | Rule::Sum { field } => {
466                let earlier = field_types
467                    .iter()
468                    .take_while(|(n, _)| n != name)
469                    .find(|(n, _)| n == field);
470                match earlier {
471                    None => out.push(R7Violation::Typing(format!(
472                        "'{name}' references field '{field}', which is not defined earlier in the clause"
473                    ))),
474                    Some((_, r)) => {
475                        let map_like = matches!(
476                            r,
477                            Rule::LwwPerSigner { .. }
478                                | Rule::LwwMap { .. }
479                                | Rule::Events { .. }
480                        );
481                        if !map_like {
482                            out.push(R7Violation::Typing(format!(
483                                "'{name}' must reference an lww-per-signer, lww-map, or events field"
484                            )));
485                        }
486                        if matches!(rule, Rule::Histogram { .. }) && matches!(r, Rule::Events { .. }) {
487                            out.push(R7Violation::Typing(format!("histogram '{name}' may not reference an events field")));
488                        }
489                        if matches!(rule, Rule::Sum { .. }) {
490                            let numeric = match r {
491                                Rule::LwwPerSigner { verb, key, .. } | Rule::Events { verb, key } => {
492                                    matches!(ty(verb, key), Some(TypeConstraint::Integer | TypeConstraint::Nonnegative))
493                                }
494                                Rule::LwwMap { verb, value, .. }  => {
495                                    matches!(ty(verb, value), Some(TypeConstraint::Integer | TypeConstraint::Nonnegative))
496                                }
497                                _ => false,
498                            };
499                            if !numeric {
500                                out.push(R7Violation::Typing(format!("sum '{name}' requires a numeric field")));
501                            }
502                        }
503                    }
504                }
505            }
506            _ => {}
507        }
508        // REQ-1907: a delete verb carries exactly the key and :replaces.
509        if let Rule::ValuesPerKey {
510            verb,
511            key,
512            delete: Some(dv),
513            ..
514        }
515        | Rule::LwwMap {
516            verb,
517            key,
518            delete: Some(dv),
519            ..
520        } = rule
521        {
522            if dv == verb {
523                out.push(R7Violation::Replaces(format!(
524                    "delete verb of '{name}' equals its writer"
525                )));
526            }
527            let kws = declared_keywords(&d.shapes, dv);
528            let expected: BTreeSet<String> = [key.clone(), String::from(RESERVED_REPLACES)]
529                .into_iter()
530                .collect();
531            if defined(dv) && kws != expected {
532                out.push(R7Violation::Replaces(format!(
533                    "delete verb '{dv}' must carry exactly :{key} and :replaces"
534                )));
535            }
536            if let (Some(a), Some(b)) = (ty(verb, key), ty(dv, key)) {
537                if a != b {
538                    out.push(R7Violation::Typing(format!(
539                        "key :{key} differs in type between '{verb}' and '{dv}'"
540                    )));
541                }
542            }
543        }
544    }
545
546    // REQ-1907: `:replaces` present exactly where the clause implies.
547    let implied = clause.replaces_verbs();
548    for p in &d.performatives {
549        let has = shape_has_replaces(&d.shapes, &p.name);
550        let should = implied.contains(p.name.as_str());
551        if has && !should {
552            out.push(R7Violation::Replaces(format!(
553                "'{}' declares :replaces but no rule makes it a writer, delete, or remove verb",
554                p.name
555            )));
556        }
557        if should && !has {
558            out.push(R7Violation::Replaces(format!(
559                "'{}' is missing the reserved :replaces field",
560                p.name
561            )));
562        }
563    }
564    // A delete verb serves one register.
565    let mut delete_owner: alloc::collections::BTreeMap<&str, &str> =
566        alloc::collections::BTreeMap::new();
567    for (name, rule) in &field_types {
568        if let Rule::ValuesPerKey {
569            verb,
570            delete: Some(dv),
571            ..
572        }
573        | Rule::LwwMap {
574            verb,
575            delete: Some(dv),
576            ..
577        } = rule
578        {
579            if let Some(prev) = delete_owner.insert(dv.as_str(), verb.as_str()) {
580                if prev != verb {
581                    out.push(R7Violation::Replaces(format!(
582                        "delete verb '{dv}' serves two registers (field '{name}')"
583                    )));
584                }
585            }
586        }
587    }
588
589    // Initial fields read only the protocol opener, without an ordering policy.
590    for (name, rule) in clause.fields() {
591        if let Rule::Initial { verb, .. } = rule {
592            if Some(verb.as_str()) != opener.as_deref() {
593                out.push(R7Violation::Typing(format!(
594                    "initial field '{name}' must name the unique protocol opener"
595                )));
596            }
597        }
598    }
599
600    // REQ-1908: domains.
601    for (verb, key, field) in clause.domains() {
602        if Some(verb) == opener.as_deref() {
603            out.push(R7Violation::Domain(format!(
604                "a domain may not filter the opener '{verb}'"
605            )));
606        }
607        if let Some(tc) = ty(verb, key) {
608            if tc != TypeConstraint::String {
609                out.push(R7Violation::Domain(format!(
610                    "domain key :{key} of '{verb}' must be a string"
611                )));
612            }
613        }
614        match clause.rule_of(field) {
615            None => out.push(R7Violation::Domain(format!(
616                "domain names undefined field '{field}'"
617            ))),
618            Some(Rule::Context { path, .. }) if crate::context::roster_role(path).is_some() => {}
619            Some(rule) => {
620                let over_opener = rule.verbs().iter().all(|v| Some(*v) == opener.as_deref());
621                if !over_opener || rule.verbs().is_empty() {
622                    out.push(R7Violation::Domain(format!(
623                        "domain field '{field}' must be a rule over the opener only"
624                    )));
625                }
626                if let Rule::Initial { verb, key } = rule {
627                    if ty(verb, key) != Some(TypeConstraint::List) {
628                        out.push(R7Violation::Domain(format!(
629                            "domain field '{field}' must be list-valued"
630                        )));
631                    }
632                } else {
633                    out.push(R7Violation::Domain(format!(
634                        "domain field '{field}' must be an `initial` over the opener's list"
635                    )));
636                }
637            }
638        }
639    }
640
641    // REQ-1927: a name that claims to be a self-address must be one. An
642    // author-chosen name is a pointer and is left alone; identity is the
643    // body hash either way (ADR-1903), and a consumer that needs
644    // content-addressed names uses `canonical::dialect_name`.
645    if d.name.starts_with(SELF_ADDRESS_PREFIX) {
646        check_name(d, &mut out);
647    }
648    out
649}
650
651/// SPEC-038 REQ-3802 / CON-3801 at installation: a threshold's name is unique
652/// among fields and thresholds; its field is declared earlier in the clause
653/// and has a carrier; every element is admitted by that carrier, never by
654/// the display (REQ-3809); and the elements are pairwise incompatible, in
655/// `O(k²)` comparisons (NFR-3800). Fail closed: the message names the
656/// offending element and carrier.
657fn check_thresholds<'a>(
658    dialect: &Dialect,
659    clause: &'a StateClause,
660    names: &mut BTreeSet<&'a str>,
661    out: &mut Vec<R7Violation>,
662) {
663    use crate::state::{Condition, Entry};
664    let mut declared: BTreeSet<&str> = BTreeSet::new();
665    for entry in &clause.entries {
666        let name = match entry {
667            Entry::Field { name, .. } => {
668                declared.insert(name.as_str());
669                continue;
670            }
671            Entry::Threshold { name, .. } | Entry::Condition { name, .. } => name,
672            _ => continue,
673        };
674        if !names.insert(name) {
675            out.push(R7Violation::Malformed(format!(
676                "duplicate field '{name}' (a threshold shares the field namespace)"
677            )));
678        }
679        match entry {
680            Entry::Threshold {
681                field, elements, ..
682            } => check_threshold_source(dialect, clause, name, field, elements, &declared, out),
683            Entry::Condition { condition, .. } => {
684                let bounds = bounds_of(dialect);
685                if condition.size() > bounds.max_list as usize {
686                    out.push(R7Violation::Bounds(format!(
687                        "{name}: condition exceeds max-list {}",
688                        bounds.max_list
689                    )));
690                }
691                fn arity(condition: &Condition) -> bool {
692                    match condition {
693                        Condition::Read { .. } => true,
694                        Condition::And(children) => {
695                            children.len() >= 2 && children.iter().all(arity)
696                        }
697                    }
698                }
699                if !arity(condition) {
700                    out.push(R7Violation::Threshold(format!(
701                        "{name}: and requires at least two children"
702                    )));
703                }
704                let mut leaves = Vec::new();
705                condition.leaves(&mut leaves);
706                for (field, element) in leaves {
707                    fn bounded(expr: &SExpr, bounds: &StateBounds) -> bool {
708                        match expr {
709                            SExpr::Atom(Atom::Str(s)) => s.len() <= bounds.max_string as usize,
710                            SExpr::Atom(Atom::Num(n)) => {
711                                n.unsigned_abs() <= bounds.max_number as u64
712                            }
713                            SExpr::List(items) => items.iter().all(|item| bounded(item, bounds)),
714                            _ => true,
715                        }
716                    }
717                    if !bounded(&element.to_sexpr(), &bounds) {
718                        out.push(R7Violation::Bounds(format!(
719                            "{name}: condition element exceeds scalar bounds"
720                        )));
721                    }
722                    check_threshold_source(
723                        dialect,
724                        clause,
725                        name,
726                        field,
727                        core::slice::from_ref(element),
728                        &declared,
729                        out,
730                    );
731                }
732            }
733            _ => {}
734        }
735    }
736}
737
738fn check_threshold_source(
739    dialect: &Dialect,
740    clause: &StateClause,
741    name: &str,
742    field: &str,
743    elements: &[crate::lattice::Element],
744    declared: &BTreeSet<&str>,
745    out: &mut Vec<R7Violation>,
746) {
747    use crate::lattice::{carrier_of, pairwise, relation};
748    let rule = if declared.contains(field) {
749        clause.rule_of(field)
750    } else if clause.rule_of(field).is_some() {
751        out.push(R7Violation::Threshold(format!(
752            "{name}: field '{field}' is declared after the threshold; declare it earlier in the clause"
753        )));
754        None
755    } else {
756        out.push(R7Violation::Threshold(format!(
757            "{name}: names undefined field '{field}'"
758        )));
759        None
760    };
761    let Some(rule) = rule else {
762        return;
763    };
764    if clause
765        .freezes()
766        .any(|(f, _, policy)| f == field && policy == crate::state::FreezePolicy::Supersede)
767    {
768        out.push(R7Violation::Threshold(format!(
769            "{name}: supersede freeze can revise '{field}'; use a separate unfrozen arrival field or the fault freeze policy"
770        )));
771        return;
772    }
773    let Some(carrier) = carrier_of(rule) else {
774        out.push(R7Violation::Threshold(format!(
775            "{name}: field '{field}' is a derived display with no carrier of its own"
776        )));
777        return;
778    };
779    let mut typed = true;
780    for e in elements {
781        if matches!(e, crate::lattice::Element::Sum(_)) {
782            let monotone = match rule {
783                Rule::Events { verb, key } => dialect
784                    .shapes
785                    .iter()
786                    .filter(|s| s.performative == *verb)
787                    .flat_map(|s| &s.rules)
788                    .any(|r| {
789                        matches!(r, ShapeRule::Require {
790                        keyword, type_constraint: Some(TypeConstraint::Nonnegative), ..
791                    } if keyword == key)
792                    }),
793                _ => false,
794            };
795            if !monotone {
796                typed = false;
797                out.push(R7Violation::Threshold(format!(
798                    "{name}: (sum …) on '{field}' can be revised; use a snapshot, freeze, or an events source whose writer requires nonnegative amounts"
799                )));
800                continue;
801            }
802        }
803        if !e.admitted_by(&carrier) {
804            typed = false;
805            out.push(R7Violation::Threshold(format!(
806                "{name}: element {} is not admitted by carrier {} of field '{field}'",
807                e.wire(),
808                carrier.name()
809            )));
810        }
811    }
812    if !typed {
813        return;
814    }
815    let compatibility = if let Rule::Lift(lift) = rule {
816        if let Some(table) = &lift.table {
817            // Precompute the largest stable projected value in each
818            // principal upper set, excluding conflict top. This takes
819            // O(n²) table comparisons once, independent of threshold count;
820            // every threshold pair below then takes constant work.
821            let projected: Vec<Option<i128>> = (0..table.elements.len())
822                .map(
823                    |i| match crate::finite::project(&lift.projection, table, i) {
824                        crate::state::Value::Int(n) => Some(n),
825                        crate::state::Value::Bool(b) => Some(i128::from(b)),
826                        _ => None,
827                    },
828                )
829                .collect();
830            let maxima: Vec<Option<i128>> = (0..table.elements.len())
831                .map(|a| {
832                    (0..table.elements.len())
833                        .filter(|&b| b != table.top && table.le(a, b))
834                        .filter_map(|b| projected[b])
835                        .max()
836                })
837                .collect();
838            let reads: Vec<Result<usize, i128>> = elements
839                .iter()
840                .map(|e| match e {
841                    crate::lattice::Element::Scalar(crate::state::Value::Str(name)) => {
842                        Ok(table.index(name).expect("typed finite element"))
843                    }
844                    crate::lattice::Element::Scalar(crate::state::Value::Int(n)) => Err(*n),
845                    crate::lattice::Element::Scalar(crate::state::Value::Bool(true)) => Err(1),
846                    _ => unreachable!("typed finite element"),
847                })
848                .collect();
849            let mut result = Ok(());
850            'pairs: for i in 0..elements.len() {
851                for j in i + 1..elements.len() {
852                    let why = if elements[i] == elements[j] {
853                        Some("duplicate")
854                    } else if match (reads[i], reads[j]) {
855                        (Ok(a), Ok(b)) => table.merge(a, b) != table.top,
856                        (Ok(a), Err(n)) | (Err(n), Ok(a)) => maxima[a].is_some_and(|v| v >= n),
857                        (Err(a), Err(b)) => maxima[table.bottom].is_some_and(|v| v >= a.max(b)),
858                    } {
859                        Some("compatible")
860                    } else {
861                        None
862                    };
863                    if let Some(why) = why {
864                        result = Err((i, j, why));
865                        break 'pairs;
866                    }
867                }
868            }
869            result
870        } else {
871            Ok(())
872        }
873    } else {
874        pairwise(elements, relation)
875    };
876    if let Err((i, j, why)) = compatibility {
877        out.push(R7Violation::Threshold(format!(
878            "{name}: elements {} and {} are {why}",
879            elements[i].wire(),
880            elements[j].wire()
881        )));
882    }
883}
884
885fn check_name(d: &Dialect, out: &mut Vec<R7Violation>) {
886    let expected = crate::canonical::dialect_name(d);
887    if d.name != expected {
888        out.push(R7Violation::Name {
889            expected,
890            found: d.name.clone(),
891        });
892    }
893}
894
895// ---------------------------------------------------------------------------
896// Message-level state shape (R.4)
897// ---------------------------------------------------------------------------
898
899fn violation(rule: &str, field: Option<&str>, detail: String) -> ShapeViolation {
900    ShapeViolation {
901        rule: String::from(rule),
902        field: field.map(|f| format!(":{f}")),
903        expected: None,
904        found: None,
905        detail,
906    }
907}
908
909fn is_scalar_value(v: &SExpr) -> bool {
910    matches!(
911        v,
912        SExpr::Atom(
913            Atom::Str(_) | Atom::Num(_) | Atom::Float(_) | Atom::Decimal(_) | Atom::Bool(_)
914        )
915    )
916}
917
918/// R7 state-shape check (SPEC-019 R.4, REQ-1911–1914): closed field sets,
919/// bounds on state-bearing fields, and the form of `:replaces`. Reads the
920/// message alone. `Ok(())` for any act of a verb the clause does not name.
921pub fn verify_state_shape(d: &Dialect, msg: &Message) -> Result<(), ShapeViolation> {
922    let Some(clause) = d.state.as_ref() else {
923        return Ok(());
924    };
925    let Some(simple) = msg.innermost_simple() else {
926        return Ok(());
927    };
928    let Some(verb) = simple.performative().map(|p| p.name().to_string()) else {
929        return Ok(());
930    };
931    if !clause.state_bearing_verbs().contains(verb.as_str()) {
932        return Ok(());
933    }
934    let bounds = bounds_of(d);
935    let declared = declared_keywords(&d.shapes, &verb);
936    let fields = keyword_fields(simple);
937
938    // Closed field set. Shape lookup reads the first keyword while state
939    // extraction keeps the last: reject ambiguous data fields before either
940    // interpretation can admit a different value (SPEC-038 REQ-3802).
941    if let Message::Simple { params, .. } = simple {
942        let mut seen_fields = BTreeSet::new();
943        let mut i = 0;
944        while i < params.len() {
945            match &params[i] {
946                SExpr::Atom(Atom::Keyword(k)) => {
947                    if !ROUTING_KEYWORDS.contains(&k.as_str()) && !seen_fields.insert(k) {
948                        return Err(violation(
949                            "closed",
950                            Some(k),
951                            "duplicate state keyword".into(),
952                        ));
953                    }
954                    if !declared.contains(k) && !ROUTING_KEYWORDS.contains(&k.as_str()) {
955                        return Err(violation(
956                            "closed",
957                            Some(k),
958                            format!("undeclared field :{k} on '{verb}'"),
959                        ));
960                    }
961                    i += 2;
962                }
963                _other => {
964                    return Err(violation(
965                        "closed",
966                        None,
967                        format!("unexpected positional parameter on '{verb}'"),
968                    ));
969                }
970            }
971        }
972    }
973
974    // Preserve the R7-only export contract by delegating clock checks to the
975    // declared shape type. Canonical recognition belongs to TypeConstraint::Hlc.
976    for (_, rule) in clause.fields() {
977        if let Some((writer, clock)) = rule.clock_field() {
978            if writer == verb {
979                let valid = fields
980                    .get(clock)
981                    .is_some_and(|value| TypeConstraint::Hlc.matches_builtin(value));
982                if !valid {
983                    return Err(violation(
984                        "hlc",
985                        Some(clock),
986                        "expected canonical hlc-<16 lower hex>-<8 lower hex> string".into(),
987                    ));
988                }
989            }
990        }
991    }
992
993    // Bounds on the fields rules and domains name.
994    let named: BTreeSet<&str> = clause
995        .data_fields()
996        .into_iter()
997        .filter(|(v, _)| *v == verb)
998        .map(|(_, k)| k)
999        .collect();
1000    for key in named {
1001        let Some(value) = fields.get(key) else {
1002            continue;
1003        };
1004        let allocation = clause.fields().any(|(_,r)|matches!(r, Rule::BoundedCounter(c) if c.ownership==crate::escrow::Ownership::Account&&c.initial_verb==verb&&(c.initial_key==key||c.headroom_key.as_deref()==Some(key))));
1005        if allocation {
1006            let parsed = crate::escrow::allocations(value)
1007                .map_err(|e| violation("allocations", Some(key), e))?;
1008            if parsed.len() > bounds.max_list as usize
1009                || parsed.iter().any(|(a, n)| {
1010                    a.len() > bounds.max_string as usize || *n > i128::from(bounds.max_number)
1011                })
1012            {
1013                return Err(violation(
1014                    "allocations",
1015                    Some(key),
1016                    "allocation bounds exceeded".into(),
1017                ));
1018            }
1019        } else if crate::escrow::recipient_field(d, &verb, key) {
1020            match value {
1021                SExpr::Atom(Atom::Symbol(s)) | SExpr::Atom(Atom::Str(s))
1022                    if s.starts_with('@')
1023                        && s.len() > 1
1024                        && s.len() <= bounds.max_string as usize => {}
1025                _ => {
1026                    return Err(violation(
1027                        "recipient",
1028                        Some(key),
1029                        "recipient must be an account key".into(),
1030                    ))
1031                }
1032            }
1033        } else {
1034            check_bounds(&verb, key, value, &bounds)?;
1035        }
1036    }
1037
1038    if let Some((_, counter)) = crate::escrow::rule_for(d, &verb) {
1039        if counter.certification.is_quorum()
1040            && !matches!(fields.get(crate::escrow::NONCE),Some(SExpr::Atom(Atom::Str(s))) if !s.is_empty() && s.len()<=256)
1041        {
1042            return Err(violation(
1043                "escrow",
1044                Some(crate::escrow::NONCE),
1045                "missing or invalid transaction nonce".into(),
1046            ));
1047        }
1048        let prev = match fields.get(crate::escrow::PREV) {
1049            Some(SExpr::Atom(Atom::Symbol(s))) if is_address(s) => s,
1050            _ => {
1051                return Err(violation(
1052                    "escrow",
1053                    Some(crate::escrow::PREV),
1054                    "missing or invalid escrow-prev".into(),
1055                ))
1056            }
1057        };
1058        let deps = match fields.get(crate::escrow::DEPS) {
1059            Some(SExpr::List(xs)) if xs.len() <= bounds.max_list as usize => xs,
1060            _ => {
1061                return Err(violation(
1062                    "escrow",
1063                    Some(crate::escrow::DEPS),
1064                    "missing or oversized escrow-deps".into(),
1065                ))
1066            }
1067        };
1068        let mut last: Option<&str> = None;
1069        for dep in deps {
1070            match dep {
1071                SExpr::Atom(Atom::Symbol(s))
1072                    if is_address(s) && s != prev && last.map_or(true, |p| p < s.as_str()) =>
1073                {
1074                    last = Some(s)
1075                }
1076                _ => {
1077                    return Err(violation(
1078                        "escrow",
1079                        Some(crate::escrow::DEPS),
1080                        "dependencies must be sorted distinct addresses".into(),
1081                    ))
1082                }
1083            }
1084        }
1085    }
1086
1087    // Compiler-owned bookkeeping is required on every replacement writer.
1088    if clause.replaces_verbs().contains(verb.as_str()) && !fields.contains_key(RESERVED_REPLACES) {
1089        return Err(violation(
1090            "replaces",
1091            Some(RESERVED_REPLACES),
1092            String::from("missing required :replaces list"),
1093        ));
1094    }
1095
1096    // `:replaces`: a list of at most max-list distinct addresses.
1097    if let Some(value) = fields.get(RESERVED_REPLACES) {
1098        let SExpr::List(items) = value else {
1099            return Err(violation(
1100                "replaces",
1101                Some(RESERVED_REPLACES),
1102                String::from(":replaces must be a list"),
1103            ));
1104        };
1105        if items.len() as u32 > bounds.max_list {
1106            return Err(violation(
1107                "replaces",
1108                Some(RESERVED_REPLACES),
1109                format!(":replaces names more than {} addresses", bounds.max_list),
1110            ));
1111        }
1112        let mut seen = BTreeSet::new();
1113        for item in items {
1114            let text = match item {
1115                SExpr::Atom(Atom::Symbol(s)) | SExpr::Atom(Atom::Str(s)) => s,
1116                _ => {
1117                    return Err(violation(
1118                        "replaces",
1119                        Some(RESERVED_REPLACES),
1120                        String::from(":replaces holds a non-address"),
1121                    ))
1122                }
1123            };
1124            if !is_address(text) {
1125                return Err(violation(
1126                    "replaces",
1127                    Some(RESERVED_REPLACES),
1128                    "invalid content address".into(),
1129                ));
1130            }
1131            if !seen.insert(text) {
1132                return Err(violation(
1133                    "replaces",
1134                    Some(RESERVED_REPLACES),
1135                    "content address named twice".into(),
1136                ));
1137            }
1138        }
1139    }
1140    Ok(())
1141}
1142
1143/// A content address as the wire spells it: `f1220` plus 64 lowercase hex.
1144pub fn is_address(s: &str) -> bool {
1145    crate::multihash::decode(s).is_some()
1146}
1147
1148#[allow(clippy::collapsible_match)]
1149fn check_bounds(
1150    verb: &str,
1151    key: &str,
1152    value: &SExpr,
1153    bounds: &StateBounds,
1154) -> Result<(), ShapeViolation> {
1155    match value {
1156        SExpr::Atom(Atom::Str(s)) => {
1157            if s.len() as u32 > bounds.max_string {
1158                return Err(violation(
1159                    "size",
1160                    Some(key),
1161                    format!(
1162                        ":{key} of '{verb}' exceeds max-string {}",
1163                        bounds.max_string
1164                    ),
1165                ));
1166            }
1167        }
1168        SExpr::Atom(Atom::Float(n)) => {
1169            if n.get() < -(bounds.max_number as f64) || n.get() > bounds.max_number as f64 {
1170                return Err(violation(
1171                    "size",
1172                    Some(key),
1173                    format!(":{key} of '{verb}' exceeds max-number"),
1174                ));
1175            }
1176        }
1177        SExpr::Atom(Atom::Decimal(n)) => {
1178            let absolute = n.as_str().trim_start_matches('-');
1179            let whole = absolute.split('.').next().unwrap();
1180            let limit = bounds.max_number.to_string();
1181            if n.as_str().len() > bounds.max_string as usize
1182                || whole.len() > limit.len()
1183                || (whole.len() == limit.len()
1184                    && (whole > limit.as_str() || (whole == limit && absolute.contains('.'))))
1185            {
1186                return Err(violation(
1187                    "size",
1188                    Some(key),
1189                    format!(":{key} of '{verb}' exceeds numeric bounds"),
1190                ));
1191            }
1192        }
1193        SExpr::Atom(Atom::Num(n)) => {
1194            if n.unsigned_abs() > bounds.max_number as u64 {
1195                return Err(violation(
1196                    "size",
1197                    Some(key),
1198                    format!(
1199                        ":{key} of '{verb}' exceeds max-number {}",
1200                        bounds.max_number
1201                    ),
1202                ));
1203            }
1204        }
1205        SExpr::List(items) => {
1206            if items.len() as u32 > bounds.max_list {
1207                return Err(violation(
1208                    "size",
1209                    Some(key),
1210                    format!(":{key} of '{verb}' exceeds max-list {}", bounds.max_list),
1211                ));
1212            }
1213            for item in items {
1214                if !is_scalar_value(item) {
1215                    return Err(violation(
1216                        "size",
1217                        Some(key),
1218                        format!(":{key} of '{verb}' holds a non-scalar element"),
1219                    ));
1220                }
1221                check_bounds(verb, key, item, bounds)?;
1222            }
1223        }
1224        _ => {}
1225    }
1226    Ok(())
1227}
1228
1229impl StateClause {
1230    /// Convenience: whether a verb is state-bearing.
1231    pub fn names_verb(&self, verb: &str) -> bool {
1232        self.state_bearing_verbs().contains(verb)
1233    }
1234}