Skip to main content

cbcl_core/
lattice.rs

1//! The state kernel as lattice terms (SPEC-038 CON-3800, first slice).
2//!
3//! Vocabulary (SPEC-038 § Vocabulary): a *contribution* `g` is what one act
4//! adds to a *carrier* `L`; the *lift* `A ↦ ⋁ g(a)` is the unique
5//! join-homomorphism out of the free join-semilattice on acts; a *display* is
6//! the post-map from the carrier to the rendered value; the R7 *fold* is the
7//! lift followed by a display, and keeps that name only as the API of
8//! [`crate::state::fold`].
9//!
10//! Every shipped R7 rule head denotes a lift followed by a display. The
11//! join half is a morphism from accepted-set union; displayed winners and
12//! signed balances remain revisable snapshots (SPEC-038 REQ-3805).
13//!
14//! `progress` and `bounded-counter` use `Term::History`, the identity lift
15//! retaining accepted acts under union. Their closure projections reuse the
16//! protocol-position and resource-DAG validators. They share the same kernel
17//! path, domain faults and freeze machinery as summarizing carriers, without
18//! pretending that their ancestor-dependent contributions are scalar deltas
19//! (SPEC-038 REQ-3808).
20//!
21//! Supersession fits the algebra by carrying two grow-only halves: `W`, the
22//! writes keyed by their group, and `R`, the `(group, address)` pairs a
23//! replacer of the same group names in `:replaces`. `current = W \ R` is a
24//! projection, not a join.
25//!
26//! Domain-governed terms retain raw accepted acts under union. Initializer
27//! evidence and contributions remain present even when a later opener
28//! conflicts. Filtering is a read operation; conflicts propagate to dependent
29//! displays and thresholds (SPEC-038 ADR-3805).
30
31#![forbid(unsafe_code)]
32
33use crate::hlc::Hlc;
34use crate::sexpr::{Atom, SExpr};
35use crate::state::{Act, Rule, StateClause, Value, RESERVED_REPLACES};
36use alloc::boxed::Box;
37use alloc::collections::{BTreeMap, BTreeSet};
38use alloc::string::String;
39use alloc::sync::Arc;
40use alloc::vec::Vec;
41
42/// The arbitration key of a clocked write: HLC, then signer, then address
43/// (SPEC-035). A chain: its join is `max`.
44#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
45pub struct Key {
46    pub hlc: Hlc,
47    pub signer: String,
48    pub address: String,
49}
50
51/// The `initial` carrier: no opener, exactly one, or a conflict with evidence
52/// (SPEC-038 ADR-3803). `⊥ ⊔ x = x`; two different openers join to ⊤.
53#[derive(Clone, Debug, PartialEq, Eq)]
54pub enum Sole {
55    Bot,
56    One(String, Option<Value>),
57    Top(BTreeSet<String>),
58}
59
60/// Lattice carriers. Every variant is a join-semilattice with a bottom; joins
61/// are only defined between the same variant.
62#[derive(Clone, Debug, PartialEq, Eq)]
63pub enum L {
64    Finite {
65        table: Arc<crate::finite::Table>,
66        index: usize,
67        evidence: BTreeSet<String>,
68    },
69    /// Boolean under `or`.
70    Bool(bool),
71    /// Addresses under union.
72    Addrs(BTreeSet<String>),
73    /// Distinct values keyed by their canonical rendering, under union.
74    Vals(BTreeMap<String, Value>),
75    /// Address → contribution (`events`), under union.
76    Entries(BTreeMap<String, Value>),
77    /// Address → integer amount, under union.
78    Amounts(BTreeMap<String, i128>),
79    /// The greatest clocked candidate.
80    Chain(Option<(Key, Option<Value>)>),
81    /// Writes: address → group rendering.
82    Writes(BTreeMap<String, String>),
83    /// Replaced: (group rendering, address).
84    Replaced(BTreeSet<(String, String)>),
85    /// The unique-opener carrier.
86    Sole(Sole),
87    /// Domain-governed contributions retain raw evidence; filtering is a
88    /// read/display operation (SPEC-038 ADR-3805).
89    History(BTreeMap<String, Act>),
90    Pair(Box<L>, Box<L>),
91}
92
93impl L {
94    /// The join. Mismatched variants join to the left operand; `factor` never
95    /// produces them.
96    pub fn join(self, other: L) -> L {
97        match (self, other) {
98            (
99                L::Finite {
100                    table,
101                    index: a,
102                    mut evidence,
103                },
104                L::Finite {
105                    table: other,
106                    index: b,
107                    evidence: right,
108                },
109            ) => {
110                if table.name != other.name {
111                    return L::Finite {
112                        table,
113                        index: a,
114                        evidence,
115                    };
116                }
117                evidence.extend(right);
118                let index = table.merge(a, b);
119                L::Finite {
120                    table,
121                    index,
122                    evidence,
123                }
124            }
125            (L::Bool(a), L::Bool(b)) => L::Bool(a || b),
126            (L::History(mut a), L::History(b)) => {
127                a.extend(b);
128                L::History(a)
129            }
130            (L::Addrs(mut a), L::Addrs(b)) => {
131                a.extend(b);
132                L::Addrs(a)
133            }
134            (L::Vals(mut a), L::Vals(b)) => {
135                a.extend(b);
136                L::Vals(a)
137            }
138            (L::Entries(mut a), L::Entries(b)) => {
139                a.extend(b);
140                L::Entries(a)
141            }
142            (L::Amounts(mut a), L::Amounts(b)) => {
143                a.extend(b);
144                L::Amounts(a)
145            }
146            (L::Chain(a), L::Chain(b)) => L::Chain(match (a, b) {
147                (None, x) | (x, None) => x,
148                (Some(x), Some(y)) => Some(if y.0 > x.0 { y } else { x }),
149            }),
150            (L::Writes(mut a), L::Writes(b)) => {
151                a.extend(b);
152                L::Writes(a)
153            }
154            (L::Replaced(mut a), L::Replaced(b)) => {
155                a.extend(b);
156                L::Replaced(a)
157            }
158            (L::Sole(a), L::Sole(b)) => L::Sole(match (a, b) {
159                (Sole::Bot, x) | (x, Sole::Bot) => x,
160                (Sole::One(a, v), Sole::One(b, w)) => {
161                    if a == b && v == w {
162                        Sole::One(a, v)
163                    } else {
164                        Sole::Top([a, b].into_iter().collect())
165                    }
166                }
167                (Sole::Top(mut t), Sole::One(a, _)) | (Sole::One(a, _), Sole::Top(mut t)) => {
168                    t.insert(a);
169                    Sole::Top(t)
170                }
171                (Sole::Top(mut t), Sole::Top(u)) => {
172                    t.extend(u);
173                    Sole::Top(t)
174                }
175            }),
176            (L::Pair(a, b), L::Pair(c, d)) => L::Pair(Box::new(a.join(*c)), Box::new(b.join(*d))),
177            (left, _) => left,
178        }
179    }
180}
181
182/// How writes are grouped for supersession and for keyed displays.
183#[derive(Clone, Debug, PartialEq, Eq)]
184pub enum Group {
185    None,
186    Signer,
187    Field(String),
188}
189
190/// A per-act contribution into a carrier (CON-3800 `contribute`).
191#[derive(Clone, Debug, PartialEq, Eq)]
192pub enum Contribute {
193    Finite {
194        table: Arc<crate::finite::Table>,
195        rows: Vec<crate::finite::Row>,
196    },
197    Flag,
198    Address,
199    Field(String),
200    Entry(String),
201    Amount(String),
202    Clocked {
203        value: String,
204        clock: String,
205    },
206    Write(Group),
207    Replaced(Group),
208    Sole(String),
209}
210
211/// Which accepted acts a lift ranges over. `raw` skips domain filters, as the
212/// `initial` head does.
213#[derive(Clone, Debug, PartialEq, Eq)]
214pub struct Select {
215    pub verb: String,
216    pub raw: bool,
217}
218
219/// A term of the algebra (CON-3800 `term`).
220#[derive(Clone, Debug, PartialEq, Eq)]
221pub enum Term {
222    Lift(Vec<Select>, Contribute),
223    Pair(Box<Term>, Box<Term>),
224    /// Reads an earlier field of the same clause; no lattice of its own.
225    Earlier(String),
226    /// Full accepted history under union; verbs identify domain dependencies.
227    History(Vec<String>),
228}
229
230/// The post-map from a carrier to the displayed value (CON-3800 `post`).
231#[derive(Clone, Debug, PartialEq, Eq)]
232pub enum Post {
233    Finite(Option<crate::finite::Projection>),
234    /// Native closure algorithm over the retained immutable history.
235    Closure(Box<Rule>),
236    Identity,
237    Size,
238    Difference,
239    Current(Box<Post>),
240    GroupBy(Group, Box<Post>),
241    PickLww {
242        value: String,
243        clock: String,
244    },
245    Distinct(String),
246    Histogram,
247    Sum,
248}
249
250/// A factored rule: a term and its post-map.
251#[derive(Clone, Debug, PartialEq, Eq)]
252pub struct Factored {
253    pub term: Term,
254    pub post: Post,
255}
256
257fn sel(verb: &str) -> Select {
258    Select {
259        verb: String::from(verb),
260        raw: false,
261    }
262}
263
264/// The denotation of a shipped head as a term (SPEC-038 ADR-3804).
265/// Only an unresolved, uninstalled finite declaration has no denotation.
266pub fn factor(rule: &Rule) -> Option<Factored> {
267    let lift = |verbs: Vec<Select>, c: Contribute| Term::Lift(verbs, c);
268    let pair = |a: Term, b: Term| Term::Pair(Box::new(a), Box::new(b));
269    let f = |term, post| Some(Factored { term, post });
270    match rule {
271        Rule::Lift(lift) => {
272            let table = Arc::new((**lift.table.as_ref()?).clone());
273            f(
274                Term::Lift(
275                    alloc::vec![sel(&lift.verb)],
276                    Contribute::Finite {
277                        table,
278                        rows: lift.rows.clone(),
279                    },
280                ),
281                Post::Finite(lift.projection.clone()),
282            )
283        }
284        Rule::Context { .. } | Rule::BoundedCounter(_) | Rule::Progress { .. } => f(
285            Term::History(rule.verbs().into_iter().map(String::from).collect()),
286            Post::Closure(Box::new(rule.clone())),
287        ),
288        Rule::Exists { verb } => f(
289            lift(alloc::vec![sel(verb)], Contribute::Flag),
290            Post::Identity,
291        ),
292        Rule::Count { verb } => f(
293            lift(alloc::vec![sel(verb)], Contribute::Address),
294            Post::Size,
295        ),
296        Rule::Events { verb, key } => f(
297            lift(alloc::vec![sel(verb)], Contribute::Entry(key.clone())),
298            Post::Identity,
299        ),
300        Rule::SetUnion { verb, key } => f(
301            lift(alloc::vec![sel(verb)], Contribute::Field(key.clone())),
302            Post::Identity,
303        ),
304        Rule::Values { verb, key } => f(
305            pair(
306                lift(alloc::vec![sel(verb)], Contribute::Write(Group::None)),
307                lift(alloc::vec![sel(verb)], Contribute::Replaced(Group::None)),
308            ),
309            Post::Current(Box::new(Post::Distinct(key.clone()))),
310        ),
311        Rule::ValuesPerKey {
312            verb,
313            key,
314            value,
315            delete,
316        } => {
317            let mut replacers = alloc::vec![sel(verb)];
318            if let Some(d) = delete {
319                replacers.push(sel(d));
320            }
321            f(
322                pair(
323                    lift(
324                        alloc::vec![sel(verb)],
325                        Contribute::Write(Group::Field(key.clone())),
326                    ),
327                    lift(replacers, Contribute::Replaced(Group::Field(key.clone()))),
328                ),
329                Post::Current(Box::new(Post::GroupBy(
330                    Group::Field(key.clone()),
331                    Box::new(Post::Distinct(value.clone())),
332                ))),
333            )
334        }
335        Rule::ObservedSet { add, remove, key } => f(
336            pair(
337                lift(
338                    alloc::vec![sel(add)],
339                    Contribute::Write(Group::Field(key.clone())),
340                ),
341                lift(
342                    alloc::vec![sel(add), sel(remove)],
343                    Contribute::Replaced(Group::Field(key.clone())),
344                ),
345            ),
346            Post::Current(Box::new(Post::Distinct(key.clone()))),
347        ),
348        Rule::Counter { inc, dec, key } => f(
349            pair(
350                lift(alloc::vec![sel(inc)], Contribute::Amount(key.clone())),
351                lift(alloc::vec![sel(dec)], Contribute::Amount(key.clone())),
352            ),
353            Post::Difference,
354        ),
355        Rule::Histogram { field } => f(Term::Earlier(field.clone()), Post::Histogram),
356        Rule::Sum { field } => f(Term::Earlier(field.clone()), Post::Sum),
357        Rule::LwwRegister { verb, key, clock } => f(
358            lift(
359                alloc::vec![sel(verb)],
360                Contribute::Clocked {
361                    value: key.clone(),
362                    clock: clock.clone(),
363                },
364            ),
365            Post::Identity,
366        ),
367        Rule::LwwPerSigner { verb, key, clock } => f(
368            pair(
369                lift(alloc::vec![sel(verb)], Contribute::Write(Group::Signer)),
370                lift(alloc::vec![sel(verb)], Contribute::Replaced(Group::Signer)),
371            ),
372            Post::Current(Box::new(Post::GroupBy(
373                Group::Signer,
374                Box::new(Post::PickLww {
375                    value: key.clone(),
376                    clock: clock.clone(),
377                }),
378            ))),
379        ),
380        Rule::LwwMap {
381            verb,
382            key,
383            value,
384            clock,
385            delete,
386        } => {
387            let mut replacers = alloc::vec![sel(verb)];
388            if let Some(d) = delete {
389                replacers.push(sel(d));
390            }
391            f(
392                pair(
393                    lift(
394                        alloc::vec![sel(verb)],
395                        Contribute::Write(Group::Field(key.clone())),
396                    ),
397                    lift(replacers, Contribute::Replaced(Group::Field(key.clone()))),
398                ),
399                Post::Current(Box::new(Post::GroupBy(
400                    Group::Field(key.clone()),
401                    Box::new(Post::PickLww {
402                        value: value.clone(),
403                        clock: clock.clone(),
404                    }),
405                ))),
406            )
407        }
408        Rule::Initial { verb, key } => f(
409            lift(
410                alloc::vec![Select {
411                    verb: verb.clone(),
412                    raw: true,
413                }],
414                Contribute::Sole(key.clone()),
415            ),
416            Post::Identity,
417        ),
418    }
419}
420
421/// The accepted acts, unique by address, with the clause's domain filters
422/// resolved (SPEC-019 ADR-1909: domains read list-valued opener fields).
423pub struct Ctx<'a> {
424    clause: &'a StateClause,
425    raw_acts: &'a [Act],
426    protocol: Option<&'a crate::protocol::CausalProtocol>,
427    acts: hashbrown::HashMap<String, &'a Act>,
428    domains: Vec<(String, String, Vec<Value>)>,
429    domain_faults: Vec<(String, Value)>,
430}
431
432impl<'a> Ctx<'a> {
433    pub fn new(clause: &'a StateClause, acts: &'a [Act]) -> Ctx<'a> {
434        Self::with_protocol(clause, acts, None)
435    }
436
437    pub fn with_protocol(
438        clause: &'a StateClause,
439        acts: &'a [Act],
440        protocol: Option<&'a crate::protocol::CausalProtocol>,
441    ) -> Ctx<'a> {
442        let mut unique: hashbrown::HashMap<String, &Act> = hashbrown::HashMap::new();
443        for a in acts {
444            unique.entry(a.address.clone()).or_insert(a);
445        }
446        let bare = Ctx {
447            clause,
448            raw_acts: acts,
449            protocol,
450            acts: unique.clone(),
451            domains: Vec::new(),
452            domain_faults: Vec::new(),
453        };
454        let mut domains = Vec::new();
455        let mut domain_faults = Vec::new();
456        for (verb, key, field) in clause.domains() {
457            let allowed = match clause.rule_of(field).and_then(factor) {
458                Some(fd) => {
459                    let value = bare.display(&fd, &[]);
460                    if value.fault_evidence().is_some() {
461                        domain_faults.push((String::from(verb), value.clone()));
462                    }
463                    match value {
464                        Value::List(items) | Value::Set(items) => items,
465                        _ => Vec::new(),
466                    }
467                }
468                None => Vec::new(),
469            };
470            domains.push((String::from(verb), String::from(key), allowed));
471        }
472        Ctx {
473            clause,
474            raw_acts: acts,
475            protocol,
476            acts: unique,
477            domains,
478            domain_faults,
479        }
480    }
481
482    fn field(act: &Act, key: &str) -> Option<Value> {
483        act.fields.get(key).map(Value::from_sexpr)
484    }
485
486    fn in_domain(&self, act: &Act) -> bool {
487        self.domains.iter().all(|(v, key, allowed)| {
488            if *v != act.verb {
489                return true;
490            }
491            match Self::field(act, key) {
492                Some(val) => {
493                    let r = val.render();
494                    allowed.iter().any(|x| x.render() == r)
495                }
496                None => false,
497            }
498        })
499    }
500
501    fn selected(&self, s: &Select) -> impl Iterator<Item = &'a Act> + '_ {
502        let verb = s.verb.clone();
503        let raw = s.raw;
504        self.acts
505            .values()
506            .copied()
507            .filter(move |a| a.verb == verb && (raw || self.in_domain(a)))
508    }
509
510    fn group_key(act: &Act, group: &Group) -> String {
511        match group {
512            Group::None => String::new(),
513            Group::Signer => act.signer.clone(),
514            Group::Field(k) => Self::field(act, k).map(|v| v.render()).unwrap_or_default(),
515        }
516    }
517
518    fn bottom(c: &Contribute) -> L {
519        match c {
520            Contribute::Finite { table, .. } => L::Finite {
521                table: table.clone(),
522                index: table.bottom,
523                evidence: BTreeSet::new(),
524            },
525            Contribute::Flag => L::Bool(false),
526            Contribute::Address => L::Addrs(BTreeSet::new()),
527            Contribute::Field(_) => L::Vals(BTreeMap::new()),
528            Contribute::Entry(_) => L::Entries(BTreeMap::new()),
529            Contribute::Amount(_) => L::Amounts(BTreeMap::new()),
530            Contribute::Clocked { .. } => L::Chain(None),
531            Contribute::Write(_) => L::Writes(BTreeMap::new()),
532            Contribute::Replaced(_) => L::Replaced(BTreeSet::new()),
533            Contribute::Sole(_) => L::Sole(Sole::Bot),
534        }
535    }
536
537    /// `g(a)`: one act's contribution.
538    fn contribute(act: &Act, c: &Contribute) -> L {
539        match c {
540            Contribute::Finite { table, rows } => {
541                let index = rows
542                    .iter()
543                    .filter(|row| act.fields.get(&row.key) == Some(&row.value))
544                    .filter_map(|row| table.index(&row.element))
545                    .fold(table.bottom, |a, b| table.merge(a, b));
546                let evidence = if index == table.bottom {
547                    BTreeSet::new()
548                } else {
549                    [act.address.clone()].into_iter().collect()
550                };
551                L::Finite {
552                    table: table.clone(),
553                    index,
554                    evidence,
555                }
556            }
557            Contribute::Flag => L::Bool(true),
558            Contribute::Address => L::Addrs([act.address.clone()].into_iter().collect()),
559            Contribute::Field(k) => L::Vals(
560                Self::field(act, k)
561                    .map(|v| [(v.render(), v)].into_iter().collect())
562                    .unwrap_or_default(),
563            ),
564            Contribute::Entry(k) => L::Entries(
565                Self::field(act, k)
566                    .map(|v| {
567                        [(
568                            act.address.clone(),
569                            Value::Pair {
570                                by: act.signer.clone(),
571                                value: Box::new(v),
572                            },
573                        )]
574                        .into_iter()
575                        .collect()
576                    })
577                    .unwrap_or_default(),
578            ),
579            Contribute::Amount(k) => L::Amounts(
580                Self::field(act, k)
581                    .and_then(|v| v.as_int())
582                    .map(|n| [(act.address.clone(), n)].into_iter().collect())
583                    .unwrap_or_default(),
584            ),
585            Contribute::Clocked { value, clock } => L::Chain(match act.fields.get(clock) {
586                Some(SExpr::Atom(Atom::Str(text))) => Hlc::parse(text).map(|hlc| {
587                    (
588                        Key {
589                            hlc,
590                            signer: act.signer.clone(),
591                            address: act.address.clone(),
592                        },
593                        Self::field(act, value),
594                    )
595                }),
596                _ => None,
597            }),
598            Contribute::Write(g) => L::Writes(
599                [(act.address.clone(), Self::group_key(act, g))]
600                    .into_iter()
601                    .collect(),
602            ),
603            Contribute::Replaced(g) => L::Replaced(match act.fields.get(RESERVED_REPLACES) {
604                Some(SExpr::List(items)) => {
605                    let k = Self::group_key(act, g);
606                    items
607                        .iter()
608                        .filter_map(|i| match i {
609                            SExpr::Atom(Atom::Symbol(a)) | SExpr::Atom(Atom::Str(a)) => {
610                                Some((k.clone(), a.clone()))
611                            }
612                            _ => None,
613                        })
614                        .collect()
615                }
616                _ => BTreeSet::new(),
617            }),
618            Contribute::Sole(k) => L::Sole(Sole::One(act.address.clone(), Self::field(act, k))),
619        }
620    }
621
622    /// The join half of a term over this context's accepted acts.
623    pub fn eval(&self, term: &Term) -> L {
624        if self.domain_governed(term) || matches!(term, Term::History(_)) {
625            return L::History(
626                self.acts
627                    .iter()
628                    .map(|(addr, act)| (addr.clone(), (*act).clone()))
629                    .collect(),
630            );
631        }
632        self.read_carrier(term)
633    }
634
635    fn domain_governed(&self, term: &Term) -> bool {
636        match term {
637            Term::Lift(selects, _) => selects
638                .iter()
639                .any(|s| !s.raw && self.domains.iter().any(|(verb, _, _)| *verb == s.verb)),
640            Term::Pair(a, b) => self.domain_governed(a) || self.domain_governed(b),
641            Term::Earlier(_) | Term::History(_) => false,
642        }
643    }
644
645    /// The successful read of retained evidence after resolving domains.
646    /// Callers check dependency faults before interpreting this carrier.
647    pub fn read_carrier(&self, term: &Term) -> L {
648        match term {
649            Term::Lift(selects, c) => {
650                let mut carrier = selects
651                    .iter()
652                    .flat_map(|s| self.selected(s))
653                    .fold(Self::bottom(c), |acc, a| acc.join(Self::contribute(a, c)));
654                if let L::Finite {
655                    table,
656                    index,
657                    evidence,
658                } = &mut carrier
659                {
660                    if *index == table.top {
661                        let verbs: Vec<_> = selects
662                            .iter()
663                            .filter(|s| !s.raw)
664                            .map(|s| s.verb.clone())
665                            .collect();
666                        evidence.extend(crate::state::domain_support_addresses(
667                            self.clause,
668                            self.raw_acts,
669                            &verbs,
670                        ));
671                    }
672                }
673                carrier
674            }
675            Term::Pair(a, b) => L::Pair(
676                Box::new(self.read_carrier(a)),
677                Box::new(self.read_carrier(b)),
678            ),
679            Term::Earlier(_) => L::Bool(false),
680            Term::History(_) => L::History(
681                self.acts
682                    .iter()
683                    .map(|(id, a)| (id.clone(), (*a).clone()))
684                    .collect(),
685            ),
686        }
687    }
688
689    /// The displayed value: the post-map applied to the join.
690    pub fn display(&self, f: &Factored, done: &[(String, Value)]) -> Value {
691        if let Some(fault) = self.term_fault(&f.term) {
692            if let Post::Closure(rule) = &f.post {
693                let own =
694                    crate::state::closure_value(self.clause, self.protocol, self.raw_acts, rule);
695                if let Some(mut evidence) = own.fault_evidence() {
696                    evidence.extend(fault.fault_evidence().unwrap_or_default());
697                    return crate::state::conflict_top("state conflicts", evidence);
698                }
699            }
700            return fault;
701        }
702        match &f.term {
703            Term::Earlier(field) => {
704                let earlier = done.iter().find(|(n, _)| n == field).map(|(_, v)| v);
705                if let Some(value) = earlier.filter(|v| v.fault_evidence().is_some()) {
706                    return value.clone();
707                }
708                match &f.post {
709                    Post::Histogram => histogram(earlier),
710                    Post::Sum => Value::Int(match earlier {
711                        Some(Value::Map(entries)) => {
712                            entries.iter().filter_map(|(_, v)| v.as_int()).sum()
713                        }
714                        _ => 0,
715                    }),
716                    _ => Value::Absent,
717                }
718            }
719            _ => self.post(&self.read_carrier(&f.term), &f.post),
720        }
721    }
722
723    fn term_fault(&self, term: &Term) -> Option<Value> {
724        let mut evidence = BTreeSet::new();
725        self.collect_term_faults(term, &mut evidence);
726        (!evidence.is_empty()).then(|| {
727            crate::state::conflict_top("initializer conflict", evidence.into_iter().collect())
728        })
729    }
730
731    fn collect_term_faults(&self, term: &Term, evidence: &mut BTreeSet<String>) {
732        match term {
733            Term::Lift(selects, contribution) => {
734                let mut initializer_fault = false;
735                for s in selects.iter().filter(|s| !s.raw) {
736                    for (_, fault) in self
737                        .domain_faults
738                        .iter()
739                        .filter(|(verb, _)| *verb == s.verb)
740                    {
741                        if let Some(addresses) = fault.fault_evidence() {
742                            initializer_fault = true;
743                            evidence.extend(addresses);
744                        }
745                    }
746                }
747                if initializer_fault && matches!(contribution, Contribute::Finite { .. }) {
748                    let verbs: Vec<_> = selects
749                        .iter()
750                        .filter(|s| !s.raw)
751                        .map(|s| s.verb.clone())
752                        .collect();
753                    evidence.extend(crate::state::domain_support_addresses(
754                        self.clause,
755                        self.raw_acts,
756                        &verbs,
757                    ));
758                    // REQ-3806: conflicting domain evidence must not replace
759                    // writers that established a finite top before the fork.
760                    // The domain is no longer uniquely selectable; retain the
761                    // finite contributions from raw accepted source history.
762                    for select in selects {
763                        for act in self.acts.values().filter(|a| a.verb == select.verb) {
764                            if let L::Finite {
765                                evidence: writers, ..
766                            } = Self::contribute(act, contribution)
767                            {
768                                evidence.extend(writers);
769                            }
770                        }
771                    }
772                }
773            }
774            Term::Pair(a, b) => {
775                self.collect_term_faults(a, evidence);
776                self.collect_term_faults(b, evidence);
777            }
778            Term::History(verbs) => {
779                for (_, fault) in self
780                    .domain_faults
781                    .iter()
782                    .filter(|(verb, _)| verbs.contains(verb))
783                {
784                    if let Some(addresses) = fault.fault_evidence() {
785                        evidence.extend(addresses);
786                    }
787                }
788            }
789            Term::Earlier(_) => {}
790        }
791    }
792
793    pub fn rule_fault(&self, rule: &Rule) -> Option<Value> {
794        factor(rule).and_then(|f| self.term_fault(&f.term))
795    }
796
797    fn post(&self, l: &L, post: &Post) -> Value {
798        match (post, l) {
799            (Post::Closure(rule), L::History(_)) => {
800                crate::state::closure_value(self.clause, self.protocol, self.raw_acts, rule)
801            }
802            (
803                Post::Finite(projection),
804                L::Finite {
805                    table,
806                    index,
807                    evidence,
808                },
809            ) => {
810                if *index == table.top {
811                    crate::state::conflict_top(
812                        "finite lattice conflict",
813                        evidence.iter().cloned().collect(),
814                    )
815                } else {
816                    crate::finite::project(projection, table, *index)
817                }
818            }
819            (Post::Identity, L::Bool(b)) => Value::Bool(*b),
820            (Post::Identity, L::Vals(m)) => Value::Set(m.values().cloned().collect()),
821            (Post::Identity, L::Entries(m)) => Value::Map(
822                m.iter()
823                    .map(|(a, v)| (Value::Str(a.clone()), v.clone()))
824                    .collect(),
825            ),
826            (Post::Identity, L::Chain(c)) => c
827                .as_ref()
828                .and_then(|(_, v)| v.clone())
829                .unwrap_or(Value::Absent),
830            (Post::Identity, L::Sole(s)) => match s {
831                Sole::One(_, v) => v.clone().unwrap_or(Value::Absent),
832                Sole::Bot => Value::Absent,
833                // ⊤ renders as a fault with its evidence (SPEC-038 REQ-3804).
834                Sole::Top(t) => {
835                    crate::state::conflict_top("opener fork", t.iter().cloned().collect())
836                }
837            },
838            (Post::Size, L::Addrs(s)) => Value::Int(s.len() as i128),
839            (Post::Difference, L::Pair(a, b)) => match (&**a, &**b) {
840                (L::Amounts(x), L::Amounts(y)) => {
841                    Value::Int(x.values().sum::<i128>() - y.values().sum::<i128>())
842                }
843                _ => Value::Absent,
844            },
845            (Post::Current(then), L::Pair(w, r)) => match (&**w, &**r) {
846                (L::Writes(writes), L::Replaced(replaced)) => {
847                    let current: Vec<&Act> = writes
848                        .iter()
849                        .filter(|(addr, group)| {
850                            !replaced.contains(&((*group).clone(), (*addr).clone()))
851                        })
852                        .filter_map(|(addr, _)| self.acts.get(addr).copied())
853                        .collect();
854                    self.over_acts(&current, then)
855                }
856                _ => Value::Absent,
857            },
858            _ => Value::Absent,
859        }
860    }
861
862    fn over_acts(&self, acts: &[&Act], post: &Post) -> Value {
863        match post {
864            Post::Distinct(key) => {
865                let mut m: BTreeMap<String, Value> = BTreeMap::new();
866                for a in acts {
867                    if let Some(v) = Self::field(a, key) {
868                        m.insert(v.render(), v);
869                    }
870                }
871                Value::Set(m.into_values().collect())
872            }
873            Post::PickLww { value, clock } => acts
874                .iter()
875                .filter_map(|a| match a.fields.get(clock) {
876                    Some(SExpr::Atom(Atom::Str(text))) => Hlc::parse(text).map(|hlc| {
877                        (
878                            Key {
879                                hlc,
880                                signer: a.signer.clone(),
881                                address: a.address.clone(),
882                            },
883                            *a,
884                        )
885                    }),
886                    _ => None,
887                })
888                .max_by(|(x, _), (y, _)| x.cmp(y))
889                .map(|(_, a)| Self::field(a, value).unwrap_or(Value::Absent))
890                .unwrap_or(Value::Absent),
891            Post::GroupBy(group, then) => {
892                let mut groups: BTreeMap<Vec<u8>, (Value, Vec<&Act>)> = BTreeMap::new();
893                for a in acts {
894                    let k = match group {
895                        Group::Signer => Value::Str(a.signer.clone()),
896                        Group::Field(key) => match Self::field(a, key) {
897                            Some(v) => v,
898                            None => continue,
899                        },
900                        Group::None => Value::Str(String::new()),
901                    };
902                    groups
903                        .entry(k.render().into_bytes())
904                        .or_insert_with(|| (k.clone(), Vec::new()))
905                        .1
906                        .push(a);
907                }
908                Value::Map(
909                    groups
910                        .into_values()
911                        .map(|(k, t)| (k, self.over_acts(&t, then)))
912                        .collect(),
913                )
914            }
915            _ => Value::Absent,
916        }
917    }
918}
919
920fn histogram(earlier: Option<&Value>) -> Value {
921    let mut counts: BTreeMap<Vec<u8>, (Value, i128)> = BTreeMap::new();
922    if let Some(Value::Map(entries)) = earlier {
923        for (_, v) in entries {
924            let v = match v {
925                Value::Pair { value, .. } => (**value).clone(),
926                other => other.clone(),
927            };
928            if v == Value::Absent {
929                continue;
930            }
931            counts
932                .entry(v.render().into_bytes())
933                .or_insert_with(|| (v.clone(), 0))
934                .1 += 1;
935        }
936    }
937    Value::Map(
938        counts
939            .into_values()
940            .map(|(v, n)| (v, Value::Int(n)))
941            .collect(),
942    )
943}
944
945/// Display fields in clause order. For progress closures, supply protocol
946/// context through [`display_clause_with_protocol`].
947pub fn display_clause(
948    clause: &StateClause,
949    acts: &[Act],
950    fallback: &[(String, Value)],
951) -> Vec<(String, Option<Value>)> {
952    display_clause_with_protocol(clause, acts, None, fallback)
953}
954
955pub fn display_clause_with_protocol(
956    clause: &StateClause,
957    acts: &[Act],
958    protocol: Option<&crate::protocol::CausalProtocol>,
959    fallback: &[(String, Value)],
960) -> Vec<(String, Option<Value>)> {
961    let ctx = Ctx::with_protocol(clause, acts, protocol);
962    let mut done: Vec<(String, Value)> = Vec::new();
963    let mut out = Vec::new();
964    for (name, rule) in clause.fields() {
965        let v = factor(rule).map(|f| ctx.display(&f, &done));
966        let for_done = v.clone().or_else(|| {
967            fallback
968                .iter()
969                .find(|(n, _)| n == name)
970                .map(|(_, v)| v.clone())
971        });
972        if let Some(v) = for_done {
973            done.push((String::from(name), v));
974        }
975        out.push((String::from(name), v));
976    }
977    out
978}
979
980// ---------------------------------------------------------------------------
981// Threshold reads (SPEC-038 REQ-3802, CON-3801)
982// ---------------------------------------------------------------------------
983
984/// The carrier a field's term lifts into, named for typing a threshold
985/// element against it (SPEC-038 REQ-3802: typed against the carrier, never
986/// the display). The two closure heads have no summarising carrier
987/// (REQ-3808); they are named by their closure so that `progress n` and a
988/// resource `fault` can be typed.
989#[derive(Clone, Debug, PartialEq, Eq)]
990pub enum Carrier {
991    Finite(Arc<crate::finite::Table>, Option<crate::finite::Projection>),
992    Bool,
993    Addrs,
994    Vals,
995    Entries,
996    Amounts,
997    Chain,
998    Writes,
999    Replaced,
1000    Sole,
1001    Pair(Box<Carrier>, Box<Carrier>),
1002    /// The act set under the `progress` closure.
1003    Progress,
1004    /// The act set under the `bounded-counter` closure.
1005    Resource,
1006}
1007
1008impl Carrier {
1009    /// The carrier's name in the wire grammar of CON-3801.
1010    pub fn name(&self) -> String {
1011        match self {
1012            Carrier::Finite(table, _) => alloc::format!("finite:{}", table.name),
1013            Carrier::Bool => String::from("bool"),
1014            Carrier::Addrs => String::from("addrs"),
1015            Carrier::Vals => String::from("vals"),
1016            Carrier::Entries => String::from("entries"),
1017            Carrier::Amounts => String::from("amounts"),
1018            Carrier::Chain => String::from("chain"),
1019            Carrier::Writes => String::from("writes"),
1020            Carrier::Replaced => String::from("replaced"),
1021            Carrier::Sole => String::from("sole"),
1022            Carrier::Pair(a, b) => alloc::format!("({} × {})", a.name(), b.name()),
1023            Carrier::Progress => String::from("progress"),
1024            Carrier::Resource => String::from("resource"),
1025        }
1026    }
1027}
1028
1029fn carrier_of_term(term: &Term) -> Option<Carrier> {
1030    match term {
1031        Term::Lift(_, c) => Some(match c {
1032            Contribute::Finite { table, .. } => Carrier::Finite(table.clone(), None),
1033            Contribute::Flag => Carrier::Bool,
1034            Contribute::Address => Carrier::Addrs,
1035            Contribute::Field(_) => Carrier::Vals,
1036            Contribute::Entry(_) => Carrier::Entries,
1037            Contribute::Amount(_) => Carrier::Amounts,
1038            Contribute::Clocked { .. } => Carrier::Chain,
1039            Contribute::Write(_) => Carrier::Writes,
1040            Contribute::Replaced(_) => Carrier::Replaced,
1041            Contribute::Sole(_) => Carrier::Sole,
1042        }),
1043        Term::Pair(a, b) => Some(Carrier::Pair(
1044            Box::new(carrier_of_term(a)?),
1045            Box::new(carrier_of_term(b)?),
1046        )),
1047        Term::Earlier(_) | Term::History(_) => None,
1048    }
1049}
1050
1051/// The carrier of a rule: that of its factored term, or the closure for the
1052/// two closure heads. `None` for a derived field (`histogram`, `sum`), which
1053/// is a display over an earlier field and has no carrier of its own.
1054pub fn carrier_of(rule: &Rule) -> Option<Carrier> {
1055    match rule {
1056        Rule::Lift(lift) => lift
1057            .table
1058            .as_ref()
1059            .map(|t| Carrier::Finite(Arc::new((**t).clone()), lift.projection.clone())),
1060        Rule::Context { path, .. } if crate::context::roster_role(path).is_some() => {
1061            Some(Carrier::Vals)
1062        }
1063        Rule::Progress { .. } => Some(Carrier::Progress),
1064        Rule::BoundedCounter(_) => Some(Carrier::Resource),
1065        _ => factor(rule).and_then(|f| carrier_of_term(&f.term)),
1066    }
1067}
1068
1069/// A threshold element (CON-3801 `element`): a named element of a carrier
1070/// that a threshold read observes being reached.
1071#[derive(Clone, Debug, PartialEq, Eq)]
1072#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1073pub enum Element {
1074    /// A bare scalar; only `#t` against `bool` is admitted.
1075    Scalar(Value),
1076    /// `(count n)`: at least `n` addresses, against `addrs`.
1077    Count(i64),
1078    /// `(member x)`: `x` present, against `vals` or `entries`.
1079    Member(Value),
1080    /// `(sum n)`: grow-only numeric events sum to at least `n`. Installation
1081    /// requires a mandatory nonnegative shape on their writer.
1082    Sum(i64),
1083    /// `(progress n)`: the progress closure has reached position `n`.
1084    Progress(i64),
1085}
1086
1087impl Element {
1088    /// The wire spelling of the element, for diagnostics.
1089    pub fn wire(&self) -> String {
1090        match self {
1091            Element::Scalar(Value::Bool(true)) => String::from("#t"),
1092            Element::Scalar(Value::Bool(false)) => String::from("#f"),
1093            Element::Scalar(v) => v.render(),
1094            Element::Count(n) => alloc::format!("(count {n})"),
1095            Element::Member(v) => alloc::format!("(member {})", v.render()),
1096            Element::Sum(n) => alloc::format!("(sum {n})"),
1097            Element::Progress(n) => alloc::format!("(progress {n})"),
1098        }
1099    }
1100
1101    /// The element as a state value that round-trips the wire form:
1102    /// `{"count":2}`, `{"member":"x"}`, `{"sum":10}`, `{"progress":3}`,
1103    /// `"fault"`, `true`.
1104    pub fn render(&self) -> Value {
1105        let keyed = |k: &str, v: Value| Value::Map(alloc::vec![(Value::Str(String::from(k)), v)]);
1106        match self {
1107            Element::Scalar(v) => v.clone(),
1108            Element::Count(n) => keyed("count", Value::Int(*n as i128)),
1109            Element::Member(v) => keyed("member", v.clone()),
1110            Element::Sum(n) => keyed("sum", Value::Int(*n as i128)),
1111            Element::Progress(n) => keyed("progress", Value::Int(*n as i128)),
1112        }
1113    }
1114
1115    /// The element in the canonical encoding of the clause.
1116    pub fn to_sexpr(&self) -> SExpr {
1117        fn scalar(v: &Value) -> SExpr {
1118            match v {
1119                Value::Str(s) => SExpr::Atom(Atom::Str(s.clone())),
1120                Value::Float(n) => SExpr::Atom(Atom::Float(*n)),
1121                Value::Decimal(n) => SExpr::Atom(Atom::Decimal(n.clone())),
1122                Value::Int(n) => SExpr::Atom(Atom::Num(*n as i64)),
1123                Value::Bool(b) => SExpr::Atom(Atom::Bool(*b)),
1124                other => SExpr::Atom(Atom::Str(other.render())),
1125            }
1126        }
1127        let sym = |x: &str| SExpr::Atom(Atom::Symbol(String::from(x)));
1128        let num = |n: i64| SExpr::Atom(Atom::Num(n));
1129        match self {
1130            Element::Scalar(v) => scalar(v),
1131            Element::Count(n) => SExpr::List(alloc::vec![sym("count"), num(*n)]),
1132            Element::Member(v) => SExpr::List(alloc::vec![sym("member"), scalar(v)]),
1133            Element::Sum(n) => SExpr::List(alloc::vec![sym("sum"), num(*n)]),
1134            Element::Progress(n) => SExpr::List(alloc::vec![sym("progress"), num(*n)]),
1135        }
1136    }
1137
1138    /// Whether the carrier admits this element (the typing table of
1139    /// CON-3801): `count n` against `addrs`; `member x` against `vals` or
1140    /// `entries`; `sum n` against nonnegative numeric `entries` (the writer
1141    /// shape is checked at installation); `progress n` against progress;
1142    /// a bare `#t` against `bool`. Faults are separate outcomes.
1143    pub fn admitted_by(&self, carrier: &Carrier) -> bool {
1144        match (self, carrier) {
1145            (Element::Scalar(Value::Str(name)), Carrier::Finite(table, _)) => {
1146                table.index(name).is_some_and(|i| i != table.top)
1147            }
1148            (Element::Scalar(Value::Int(_)), Carrier::Finite(_, Some(project))) => {
1149                project.stable
1150                    && project
1151                        .rows
1152                        .iter()
1153                        .all(|(_, v)| matches!(v, SExpr::Atom(Atom::Num(_))))
1154            }
1155            (Element::Scalar(Value::Bool(true)), Carrier::Finite(_, Some(project))) => {
1156                project.stable
1157                    && project
1158                        .rows
1159                        .iter()
1160                        .all(|(_, v)| matches!(v, SExpr::Atom(Atom::Bool(_))))
1161            }
1162            (Element::Scalar(Value::Bool(true)), Carrier::Bool) => true,
1163            (Element::Count(n), Carrier::Addrs) => *n >= 0,
1164            (Element::Member(v), Carrier::Vals | Carrier::Entries) => {
1165                matches!(
1166                    v,
1167                    Value::Str(_)
1168                        | Value::Int(_)
1169                        | Value::Float(_)
1170                        | Value::Decimal(_)
1171                        | Value::Bool(_)
1172                )
1173            }
1174            (Element::Sum(_), Carrier::Entries) => true,
1175            (Element::Progress(n), Carrier::Progress) => *n >= 0,
1176            _ => false,
1177        }
1178    }
1179
1180    /// `self ≤ σ`: the element is reached by a carrier element.
1181    pub fn le(&self, l: &L) -> bool {
1182        match (self, l) {
1183            (_, L::Finite { table, index, .. }) => self.finite_read(table, *index, &None),
1184            (Element::Scalar(Value::Bool(true)), L::Bool(b)) => *b,
1185            (Element::Count(n), L::Addrs(s)) => s.len() as i64 >= *n,
1186            (Element::Member(v), L::Vals(m)) => m.contains_key(&v.render()),
1187            (Element::Member(v), L::Entries(m)) => {
1188                let want = v.render();
1189                m.values().any(|e| match e {
1190                    Value::Pair { value, .. } => value.render() == want,
1191                    other => other.render() == want,
1192                })
1193            }
1194            (Element::Sum(n), L::Amounts(m)) => m.values().sum::<i128>() >= *n as i128,
1195            (Element::Sum(n), L::Entries(m)) => {
1196                m.values().filter_map(Value::as_int).sum::<i128>() >= *n as i128
1197            }
1198            _ => false,
1199        }
1200    }
1201
1202    pub fn finite_read(
1203        &self,
1204        table: &crate::finite::Table,
1205        index: usize,
1206        projection: &Option<crate::finite::Projection>,
1207    ) -> bool {
1208        if index == table.top {
1209            return false;
1210        }
1211        match self {
1212            Element::Scalar(Value::Str(name)) => {
1213                table.index(name).is_some_and(|i| table.le(i, index))
1214            }
1215            Element::Scalar(Value::Int(n)) if projection.as_ref().is_some_and(|p| p.stable) => {
1216                matches!(crate::finite::project(projection,table,index), Value::Int(value) if value >= *n)
1217            }
1218            Element::Scalar(Value::Bool(true)) if projection.as_ref().is_some_and(|p| p.stable) => {
1219                matches!(
1220                    crate::finite::project(projection, table, index),
1221                    Value::Bool(true)
1222                )
1223            }
1224            _ => false,
1225        }
1226    }
1227
1228    pub fn le_with_post(&self, l: &L, post: &Post) -> bool {
1229        if let (L::Finite { table, index, .. }, Post::Finite(projection)) = (l, post) {
1230            self.finite_read(table, *index, projection)
1231        } else {
1232            self.le(l)
1233        }
1234    }
1235
1236    /// The element is reached by a closure head's display (REQ-3808): the
1237    /// progress integer has reached `n`. Faults are checked separately.
1238    /// The closure heads have no summarising carrier, so their ⊤ and their
1239    /// position are read from the display, which is monotone as proved in
1240    /// SPEC-034 and SPEC-019 CON-1908.
1241    pub fn le_display(&self, shown: &Value) -> bool {
1242        match (self, shown) {
1243            (Element::Progress(n), Value::Int(i)) => *i >= *n as i128,
1244            (Element::Member(member), Value::Set(values)) => values.contains(member),
1245            _ => false,
1246        }
1247    }
1248}
1249
1250/// How two elements of one threshold set relate (REQ-3802): `None` when
1251/// they are incompatible (no element other than ⊤ lies above both),
1252/// `Some("duplicate")` when equal, `Some("compatible")` otherwise. On the
1253/// chains (`count`, `sum`, `progress`) any two elements are comparable, hence
1254/// compatible; two members are compatible, since the set of both lies above
1255/// each. A numeric event member and its sum can also be reached together.
1256pub fn relation(a: &Element, b: &Element) -> Option<&'static str> {
1257    if a == b {
1258        return Some("duplicate");
1259    }
1260    match (a, b) {
1261        (Element::Count(_), Element::Count(_))
1262        | (Element::Sum(_), Element::Sum(_))
1263        | (Element::Progress(_), Element::Progress(_))
1264        | (Element::Member(_), Element::Member(_))
1265        | (Element::Member(_), Element::Sum(_))
1266        | (Element::Sum(_), Element::Member(_))
1267        | (Element::Scalar(_), Element::Scalar(_)) => Some("compatible"),
1268        _ => None,
1269    }
1270}
1271
1272/// Some element other than ⊤ lies above both.
1273pub fn compatible(a: &Element, b: &Element) -> bool {
1274    relation(a, b).is_some()
1275}
1276
1277/// The pairwise-incompatibility check of a threshold set in `O(k²)`
1278/// comparisons (NFR-3800): the first pair `rel` reports as related, as
1279/// `(i, j, why)`, or `Ok`.
1280pub fn pairwise(
1281    elements: &[Element],
1282    mut rel: impl FnMut(&Element, &Element) -> Option<&'static str>,
1283) -> Result<(), (usize, usize, &'static str)> {
1284    for i in 0..elements.len() {
1285        for j in (i + 1)..elements.len() {
1286            if let Some(why) = rel(&elements[i], &elements[j]) {
1287                return Err((i, j, why));
1288            }
1289        }
1290    }
1291    Ok(())
1292}