Skip to main content

logicaffeine_compile/semantics/
crdt.rs

1//! CRDT runtime values for the tree-walker interpreter.
2//!
3//! The compiled (AOT) tier lowers a `Shared` struct's collection fields to the real
4//! `logicaffeine_data::crdt` types — `ORSet`, `RGA`, `MVRegister` — and runs their full
5//! convergent semantics. For the interpreter to MEAN THE SAME THING as the compiler
6//! (the futamura invariant the cross-tier differential tests lock), it holds those very
7//! same types, not a lookalike `Set`/`List`. Merge is then concurrent-correct by
8//! construction: both tiers call into one `Merge` implementation, so there is no second
9//! copy of the convergence logic that could drift.
10//!
11//! The language's shared collections are homogeneous over a concrete element type
12//! (`SharedSet of Text`, `… of Int`) exactly as the compiled tier's `ORSet<String>` is.
13//! [`CrdtScalar`] is the dynamically-typed element that covers every element type the
14//! surface syntax can name; it is `Hash + Eq + Ord + Clone`, so it satisfies the
15//! data-crate CRDT bounds.
16
17use crate::interpreter::RuntimeValue;
18use logicaffeine_data::crdt::{
19    DeltaCrdt, GCounter, LatestWrite, MVRegister, Merge, ORMap, ORSet, PNCounter, RemoveWins,
20    ReplicaId, VClock, RGA,
21};
22use std::sync::atomic::{AtomicU64, Ordering};
23
24/// A monotonic source of replica ids for CRDTs the interpreter constructs. Each `new`
25/// shared collection gets a DISTINCT id, so two replicas built in one program (then
26/// merged) carry independent causal histories — the precondition for correct OR-Set /
27/// RGA convergence. The absolute id value never affects observable output (it only tags
28/// internal causal metadata), so a process-global counter keeps every run deterministic.
29static REPLICA_SEQ: AtomicU64 = AtomicU64::new(1);
30
31/// Allocate the next distinct replica id.
32pub fn next_replica_id() -> ReplicaId {
33    REPLICA_SEQ.fetch_add(1, Ordering::Relaxed)
34}
35
36/// A scalar CRDT element. CRDT collections are homogeneous, so a collection only ever
37/// holds one of these variants in practice; the enum exists because the interpreter is
38/// dynamically typed and the element type is not threaded through `struct_defs`.
39#[derive(
40    Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, serde::Serialize, serde::Deserialize,
41)]
42pub enum CrdtScalar {
43    Int(i64),
44    Text(String),
45    Bool(bool),
46}
47
48/// The placeholder a map entry holds before its first write merges in: a `LatestWrite` at stamp 0,
49/// which every real write (stamp ≥ 1) outranks, so the placeholder is never observed.
50impl Default for CrdtScalar {
51    fn default() -> Self {
52        CrdtScalar::Int(0)
53    }
54}
55
56impl CrdtScalar {
57    /// Project a [`RuntimeValue`] onto a CRDT element. Only the scalar types the surface
58    /// syntax can put in a shared collection are accepted; anything else is a type error
59    /// at the seam (never a silent coercion).
60    pub fn from_runtime(value: &RuntimeValue) -> Result<CrdtScalar, String> {
61        match value {
62            RuntimeValue::Int(n) => Ok(CrdtScalar::Int(*n)),
63            RuntimeValue::Text(s) => Ok(CrdtScalar::Text((**s).clone())),
64            RuntimeValue::Bool(b) => Ok(CrdtScalar::Bool(*b)),
65            other => Err(format!(
66                "a shared collection holds Int, Text, or Bool elements, not {}",
67                other.type_name()
68            )),
69        }
70    }
71
72    /// Reconstitute a [`RuntimeValue`] from a CRDT element.
73    pub fn to_runtime(&self) -> RuntimeValue {
74        match self {
75            CrdtScalar::Int(n) => RuntimeValue::Int(*n),
76            CrdtScalar::Text(s) => RuntimeValue::Text(std::rc::Rc::new(s.clone())),
77            CrdtScalar::Bool(b) => RuntimeValue::Bool(*b),
78        }
79    }
80
81    /// The canonical `Show` rendering of an element — matches how the compiled tier
82    /// prints the same scalar.
83    pub fn render(&self) -> String {
84        match self {
85            CrdtScalar::Int(n) => n.to_string(),
86            CrdtScalar::Text(s) => s.clone(),
87            CrdtScalar::Bool(b) => b.to_string(),
88        }
89    }
90}
91
92/// Every kind of CRDT the language has — the ONE table for what each is called in source, the code a
93/// `NewCrdt` op carries in bytecode, and the tag its full state / deltas carry on the wire. Both codes
94/// are stable wire formats: never renumber one.
95#[derive(Debug, Clone, Copy, PartialEq, Eq)]
96pub enum CrdtKind {
97    Set,
98    SetRemoveWins,
99    Seq,
100    Register,
101    Counter,
102    PnCounter,
103    Map,
104}
105
106impl CrdtKind {
107    pub const ALL: [CrdtKind; 7] = [
108        CrdtKind::Set,
109        CrdtKind::SetRemoveWins,
110        CrdtKind::Seq,
111        CrdtKind::Register,
112        CrdtKind::Counter,
113        CrdtKind::PnCounter,
114        CrdtKind::Map,
115    ];
116
117    /// The CRDT a declared field type names, or `None` for a type that is not one.
118    pub fn of_type_name(name: &str) -> Option<CrdtKind> {
119        Some(match name {
120            "SharedSet" | "ORSet" | "SharedSet_AddWins" => CrdtKind::Set,
121            "SharedSet_RemoveWins" => CrdtKind::SetRemoveWins,
122            "SharedSequence" | "RGA" | "SharedSequence_YATA" | "CollaborativeSequence" => {
123                CrdtKind::Seq
124            }
125            "ConvergentCount" | "GCounter" => CrdtKind::Counter,
126            "Tally" | "PNCounter" => CrdtKind::PnCounter,
127            "SharedMap" | "ORMap" => CrdtKind::Map,
128            _ => return None,
129        })
130    }
131
132    /// Whether `backend` lowers this CRDT — single-replica, running identically to the interpreter and
133    /// the VM. [`crate::compile::refuse_unlinkable`] refuses a program that builds a kind its backend
134    /// answers `false` for, naming the type. Exhaustive over kind × backend with no wildcard, so a new
135    /// kind or a new backend does not compile until every pair is decided; `crdt_backend_lock` runs
136    /// every pair and holds each answer to what the backend actually does.
137    pub const fn lowered_by(self, backend: crate::compile::Backend) -> bool {
138        use crate::compile::Backend;
139        match self {
140            CrdtKind::Set => match backend {
141                Backend::C => false,
142                Backend::CFromAst => false,
143                Backend::RiscV => false,
144                Backend::WebAssembly => true,
145                Backend::SoftCore => false,
146            },
147            CrdtKind::SetRemoveWins => match backend {
148                Backend::C => false,
149                Backend::CFromAst => false,
150                Backend::RiscV => false,
151                Backend::WebAssembly => true,
152                Backend::SoftCore => false,
153            },
154            CrdtKind::Seq => match backend {
155                Backend::C => true,
156                Backend::CFromAst => true,
157                Backend::RiscV => true,
158                Backend::WebAssembly => true,
159                Backend::SoftCore => false,
160            },
161            CrdtKind::Register => match backend {
162                Backend::C => true,
163                Backend::CFromAst => true,
164                Backend::RiscV => true,
165                Backend::WebAssembly => true,
166                Backend::SoftCore => true,
167            },
168            CrdtKind::Counter => match backend {
169                Backend::C => true,
170                Backend::CFromAst => true,
171                Backend::RiscV => true,
172                Backend::WebAssembly => true,
173                Backend::SoftCore => false,
174            },
175            CrdtKind::PnCounter => match backend {
176                Backend::C => true,
177                Backend::CFromAst => true,
178                Backend::RiscV => true,
179                Backend::WebAssembly => true,
180                Backend::SoftCore => false,
181            },
182            CrdtKind::Map => match backend {
183                Backend::C => false,
184                Backend::CFromAst => false,
185                Backend::RiscV => false,
186                Backend::WebAssembly => true,
187                Backend::SoftCore => false,
188            },
189        }
190    }
191
192    /// A fresh, empty replica of this kind with its own replica id.
193    pub fn fresh(self) -> CrdtValue {
194        let replica = next_replica_id();
195        match self {
196            CrdtKind::Set => CrdtValue::new_set(replica),
197            CrdtKind::SetRemoveWins => CrdtValue::new_set_remove_wins(replica),
198            CrdtKind::Seq => CrdtValue::new_seq(replica),
199            CrdtKind::Register => CrdtValue::new_register(replica),
200            CrdtKind::Counter => CrdtValue::new_counter(replica),
201            CrdtKind::PnCounter => CrdtValue::new_pn_counter(replica),
202            CrdtKind::Map => CrdtValue::new_map(replica),
203        }
204    }
205
206    /// The `kind` a `NewCrdt` op carries in bytecode.
207    pub const fn new_crdt_code(self) -> u8 {
208        match self {
209            CrdtKind::Set => 0,
210            CrdtKind::Seq => 1,
211            CrdtKind::Register => 2,
212            CrdtKind::SetRemoveWins => 3,
213            CrdtKind::Counter => 4,
214            CrdtKind::PnCounter => 5,
215            CrdtKind::Map => 6,
216        }
217    }
218
219    pub fn from_new_crdt_code(code: u8) -> Option<CrdtKind> {
220        Self::ALL.into_iter().find(|k| k.new_crdt_code() == code)
221    }
222
223    /// The tag leading a full-state or delta payload.
224    pub const fn state_tag(self) -> u8 {
225        match self {
226            CrdtKind::Set => 0,
227            CrdtKind::SetRemoveWins => 1,
228            CrdtKind::Seq => 2,
229            CrdtKind::Register => 3,
230            CrdtKind::Counter => 4,
231            CrdtKind::PnCounter => 5,
232            CrdtKind::Map => 6,
233        }
234    }
235
236    pub fn from_state_tag(tag: u8) -> Option<CrdtKind> {
237        Self::ALL.into_iter().find(|k| k.state_tag() == tag)
238    }
239
240    /// The name a program declares it by.
241    pub const fn type_name(self) -> &'static str {
242        match self {
243            CrdtKind::Set => "SharedSet",
244            CrdtKind::SetRemoveWins => "SharedSet (RemoveWins)",
245            CrdtKind::Seq => "SharedSequence",
246            CrdtKind::Register => "Divergent",
247            CrdtKind::Counter => "ConvergentCount",
248            CrdtKind::PnCounter => "Tally",
249            CrdtKind::Map => "SharedMap",
250        }
251    }
252
253    /// Why a backend that does not implement this CRDT refuses a program that uses it.
254    pub fn refusal(self, backend: &str) -> String {
255        format!(
256            "`{}` is a CRDT the {backend} backend does not implement — run the program on the \
257             interpreter or the VM, or build it with the Rust tier (`largo build`)",
258            self.type_name()
259        )
260    }
261}
262
263/// A live CRDT held by the interpreter. Wraps the actual `logicaffeine_data` type, so its
264/// convergence behaviour is identical to the compiled tier's by construction.
265#[derive(Debug, Clone)]
266pub enum CrdtValue {
267    /// `SharedSet of T` / `SharedSet (AddWins)` — observed-remove set, add-wins on a
268    /// concurrent add/remove of the same element.
269    Set(ORSet<CrdtScalar>),
270    /// `SharedSet (RemoveWins)` — observed-remove set, remove-wins on a concurrent
271    /// add/remove (e.g. an access-revocation / block list).
272    SetRemoveWins(ORSet<CrdtScalar, RemoveWins>),
273    /// `SharedSequence of T` — replicated growable array (`RGA`). Stable, convergent
274    /// insertion order.
275    Seq(RGA<CrdtScalar>),
276    /// `Divergent T` — multi-value register (`MVRegister`). Keeps concurrent writes until
277    /// one is resolved.
278    Register(MVRegister<CrdtScalar>),
279    /// `ConvergentCount` — grow-only counter (`GCounter`): each replica owns a slot, the value
280    /// is the sum, and merge is per-replica MAX. State-based ⇒ IDEMPOTENT: redelivering the same
281    /// remote state never double-counts (the very property a bare-`Int` op-based counter lacks).
282    Counter(GCounter),
283    /// `Tally` — increment/decrement counter (`PNCounter`): two G-Counters (increments and
284    /// decrements), value = Σinc − Σdec, merge per-replica MAX on both. Idempotent like `Counter`.
285    PnCounter(PNCounter),
286    /// `SharedMap from K to V` — observed-remove keys (add-wins), each value a Lamport-stamped
287    /// last-writer register (`ORMap<K, LatestWrite<V>>`), exactly the compiled tier's map.
288    Map(ORMap<CrdtScalar, LatestWrite<CrdtScalar>>),
289}
290
291impl CrdtValue {
292    pub fn new_set(replica: ReplicaId) -> CrdtValue {
293        CrdtValue::Set(ORSet::new(replica))
294    }
295
296    pub fn new_set_remove_wins(replica: ReplicaId) -> CrdtValue {
297        CrdtValue::SetRemoveWins(ORSet::new(replica))
298    }
299
300    pub fn new_seq(replica: ReplicaId) -> CrdtValue {
301        CrdtValue::Seq(RGA::new(replica))
302    }
303
304    pub fn new_register(replica: ReplicaId) -> CrdtValue {
305        CrdtValue::Register(MVRegister::new(replica))
306    }
307
308    pub fn new_counter(replica: ReplicaId) -> CrdtValue {
309        CrdtValue::Counter(GCounter::with_replica_id(replica))
310    }
311
312    pub fn new_pn_counter(replica: ReplicaId) -> CrdtValue {
313        CrdtValue::PnCounter(PNCounter::with_replica_id(replica))
314    }
315
316    pub fn new_map(replica: ReplicaId) -> CrdtValue {
317        CrdtValue::Map(ORMap::new(replica))
318    }
319
320    /// `Set <map>[key] to value`.
321    pub fn map_put(&mut self, key: &RuntimeValue, value: &RuntimeValue) -> Result<(), String> {
322        match self {
323            CrdtValue::Map(m) => {
324                m.put(
325                    CrdtScalar::from_runtime(key)?,
326                    CrdtScalar::from_runtime(value)?,
327                );
328                Ok(())
329            }
330            other => Err(format!("cannot set a key of a {}", other.kind())),
331        }
332    }
333
334    /// `<map>[key]` — the value under a PRESENT key; a missing key traps exactly as a `Map`'s does.
335    pub fn map_get(&self, key: &RuntimeValue) -> Result<RuntimeValue, String> {
336        match self {
337            CrdtValue::Map(m) => m
338                .value(&CrdtScalar::from_runtime(key)?)
339                .map(CrdtScalar::to_runtime)
340                .ok_or_else(|| {
341                    logicaffeine_data::failure::key_not_found(key.to_display_string().as_str())
342                }),
343            other => Err(format!("cannot index a {} by key", other.kind())),
344        }
345    }
346
347    /// `Increase/Decrease <counter> by N` — bump this replica's own slot. A grow-only
348    /// `ConvergentCount` rejects a decrement (that is what a `Tally` is for); a `Tally` takes both.
349    /// The per-replica slot is what makes a later merge idempotent.
350    pub fn bump(&mut self, amount: i64) -> Result<(), String> {
351        match self {
352            CrdtValue::Counter(c) => {
353                if amount < 0 {
354                    return Err(
355                        "a ConvergentCount is grow-only — use a Tally to decrement".to_string()
356                    );
357                }
358                c.increment(amount as u64);
359                Ok(())
360            }
361            CrdtValue::PnCounter(c) => {
362                if amount >= 0 {
363                    c.increment(amount as u64);
364                } else {
365                    c.decrement(amount.unsigned_abs());
366                }
367                Ok(())
368            }
369            other => Err(format!("cannot increment a {}", other.kind())),
370        }
371    }
372
373    /// The integer value of a counter (`GCounter` sum, or `PNCounter` inc−dec); `None` for a
374    /// non-counter CRDT. This is how a counter reads as a plain number for `Show` and comparison.
375    pub fn counter_value(&self) -> Option<i64> {
376        match self {
377            CrdtValue::Counter(c) => Some(c.value() as i64),
378            CrdtValue::PnCounter(c) => Some(c.value()),
379            _ => None,
380        }
381    }
382
383    /// Which CRDT this is.
384    pub fn crdt_kind(&self) -> CrdtKind {
385        match self {
386            CrdtValue::Set(_) => CrdtKind::Set,
387            CrdtValue::SetRemoveWins(_) => CrdtKind::SetRemoveWins,
388            CrdtValue::Seq(_) => CrdtKind::Seq,
389            CrdtValue::Register(_) => CrdtKind::Register,
390            CrdtValue::Counter(_) => CrdtKind::Counter,
391            CrdtValue::PnCounter(_) => CrdtKind::PnCounter,
392            CrdtValue::Map(_) => CrdtKind::Map,
393        }
394    }
395
396    /// The CRDT kind, used for type errors and `type_name`.
397    pub fn kind(&self) -> &'static str {
398        match self {
399            CrdtValue::Set(_) | CrdtValue::SetRemoveWins(_) => "SharedSet",
400            CrdtValue::Seq(_) => "SharedSequence",
401            CrdtValue::Register(_) => "Divergent",
402            CrdtValue::Counter(_) => "ConvergentCount",
403            CrdtValue::PnCounter(_) => "Tally",
404            CrdtValue::Map(_) => "SharedMap",
405        }
406    }
407
408    /// `Add element to <set>` — insert into the observed-remove set.
409    pub fn insert(&mut self, value: &RuntimeValue) -> Result<(), String> {
410        let e = CrdtScalar::from_runtime(value)?;
411        match self {
412            CrdtValue::Set(s) => Ok(s.insert(e)),
413            CrdtValue::SetRemoveWins(s) => Ok(s.insert(e)),
414            other => Err(format!("cannot add an element to a {}", other.kind())),
415        }
416    }
417
418    /// `Remove element from <set>` / `Remove key from <map>` — observed-remove deletion.
419    pub fn remove(&mut self, value: &RuntimeValue) -> Result<(), String> {
420        let e = CrdtScalar::from_runtime(value)?;
421        match self {
422            CrdtValue::Set(s) => Ok(s.remove(&e)),
423            CrdtValue::SetRemoveWins(s) => Ok(s.remove(&e)),
424            CrdtValue::Map(m) => Ok(m.remove(&e)),
425            other => Err(format!("cannot remove an element from a {}", other.kind())),
426        }
427    }
428
429    /// `<set> contains element` / `<map> contains key` — observed-remove membership.
430    pub fn contains(&self, value: &RuntimeValue) -> Result<bool, String> {
431        let e = CrdtScalar::from_runtime(value)?;
432        match self {
433            CrdtValue::Set(s) => Ok(s.contains(&e)),
434            CrdtValue::SetRemoveWins(s) => Ok(s.contains(&e)),
435            CrdtValue::Map(m) => Ok(m.contains_key(&e)),
436            other => Err(format!("a {} has no membership test", other.kind())),
437        }
438    }
439
440    /// `Append element to <sequence>` — RGA append at the end.
441    pub fn append(&mut self, value: &RuntimeValue) -> Result<(), String> {
442        match self {
443            CrdtValue::Seq(s) => {
444                s.append(CrdtScalar::from_runtime(value)?);
445                Ok(())
446            }
447            other => Err(format!("cannot append to a {}", other.kind())),
448        }
449    }
450
451    /// `Set <register> to value` / `Resolve <register> to value` — the divergent register
452    /// takes a value that dominates all concurrent ones.
453    pub fn resolve(&mut self, value: &RuntimeValue) -> Result<(), String> {
454        match self {
455            CrdtValue::Register(r) => {
456                r.resolve(CrdtScalar::from_runtime(value)?);
457                Ok(())
458            }
459            other => Err(format!("cannot resolve a {}", other.kind())),
460        }
461    }
462
463    /// `length of <collection>` — element count (set cardinality or sequence length).
464    pub fn len(&self) -> usize {
465        match self {
466            CrdtValue::Set(s) => s.len(),
467            CrdtValue::SetRemoveWins(s) => s.len(),
468            CrdtValue::Seq(s) => s.len(),
469            CrdtValue::Register(r) => r.values().len(),
470            CrdtValue::Map(m) => m.len(),
471            // A counter is a scalar, not a collection — it has no cardinality.
472            CrdtValue::Counter(_) | CrdtValue::PnCounter(_) => 0,
473        }
474    }
475
476    pub fn is_empty(&self) -> bool {
477        self.len() == 0
478    }
479
480    /// The elements as runtime values, in convergent order for a sequence and sorted for a
481    /// set (sets have no intrinsic order — sorting makes the rendering deterministic).
482    pub fn to_runtime_vec(&self) -> Vec<RuntimeValue> {
483        match self {
484            CrdtValue::Set(s) => {
485                let mut elems: Vec<&CrdtScalar> = s.iter().collect();
486                elems.sort();
487                elems.into_iter().map(CrdtScalar::to_runtime).collect()
488            }
489            CrdtValue::SetRemoveWins(s) => {
490                let mut elems: Vec<&CrdtScalar> = s.iter().collect();
491                elems.sort();
492                elems.into_iter().map(CrdtScalar::to_runtime).collect()
493            }
494            CrdtValue::Seq(s) => s.to_vec().iter().map(CrdtScalar::to_runtime).collect(),
495            CrdtValue::Register(r) => {
496                let mut vals: Vec<&CrdtScalar> = r.values();
497                vals.sort();
498                vals.into_iter().map(CrdtScalar::to_runtime).collect()
499            }
500            // A map's elements are its `(key, value)` pairs in key order — what `Repeat for` visits.
501            CrdtValue::Map(m) => m
502                .sorted_entries()
503                .into_iter()
504                .map(|(k, v)| {
505                    RuntimeValue::Tuple(std::rc::Rc::new(vec![
506                        k.to_runtime(),
507                        v.get().to_runtime(),
508                    ]))
509                })
510                .collect(),
511            // A counter's "elements" view is its single integer value (used only as a fallback;
512            // `render`/`crdt_values_equal` handle counters directly).
513            CrdtValue::Counter(_) | CrdtValue::PnCounter(_) => {
514                vec![RuntimeValue::Int(self.counter_value().unwrap_or(0))]
515            }
516        }
517    }
518
519    /// The resolved value of a register — the single current value, or `None` while it is
520    /// empty or still divergent (multiple concurrent values).
521    pub fn register_value(&self) -> Option<RuntimeValue> {
522        match self {
523            CrdtValue::Register(r) => {
524                let vals = r.values();
525                if vals.len() == 1 {
526                    Some(vals[0].to_runtime())
527                } else {
528                    None
529                }
530            }
531            _ => None,
532        }
533    }
534
535    /// Merge another CRDT of the SAME kind into this one (the convergent join). Mismatched
536    /// kinds are a type error rather than a silent no-op.
537    pub fn merge(&mut self, other: &CrdtValue) -> Result<(), String> {
538        match (self, other) {
539            (CrdtValue::Set(a), CrdtValue::Set(b)) => {
540                a.merge(b);
541                Ok(())
542            }
543            (CrdtValue::SetRemoveWins(a), CrdtValue::SetRemoveWins(b)) => {
544                a.merge(b);
545                Ok(())
546            }
547            (CrdtValue::Seq(a), CrdtValue::Seq(b)) => {
548                a.merge(b);
549                Ok(())
550            }
551            (CrdtValue::Register(a), CrdtValue::Register(b)) => {
552                a.merge(b);
553                Ok(())
554            }
555            // Per-replica MAX (idempotent) — the join that never double-counts a redelivered state.
556            (CrdtValue::Counter(a), CrdtValue::Counter(b)) => {
557                a.merge(b);
558                Ok(())
559            }
560            (CrdtValue::PnCounter(a), CrdtValue::PnCounter(b)) => {
561                a.merge(b);
562                Ok(())
563            }
564            (CrdtValue::Map(a), CrdtValue::Map(b)) => {
565                a.merge(b);
566                Ok(())
567            }
568            (a, b) => Err(format!("cannot merge a {} with a {}", a.kind(), b.kind())),
569        }
570    }
571
572    /// The current causal version (vector clock) — every update this replica has observed. The
573    /// δ-CRDT `mergeable` send remembers the version it last shipped to a peer and ships only the
574    /// delta SINCE that version, so a large set/sequence syncs its few NEW entries, not its whole
575    /// state. Idempotent + commutative, so reordering or redelivering deltas still converges.
576    pub fn version(&self) -> VClock {
577        match self {
578            CrdtValue::Set(s) => s.version(),
579            CrdtValue::SetRemoveWins(s) => s.version(),
580            CrdtValue::Seq(s) => s.version(),
581            CrdtValue::Register(s) => s.version(),
582            CrdtValue::PnCounter(s) => s.version(),
583            CrdtValue::Map(s) => s.version(),
584            // A `GCounter` keeps no vector clock; its full state is tiny, so the sync ships it whole
585            // (a valid state-based delta) — always current, and idempotent to re-apply.
586            CrdtValue::Counter(_) => VClock::new(),
587        }
588    }
589
590    /// Serialize the changes since `since` as a KIND-TAGGED delta payload — far smaller than the
591    /// full state when little changed. `None` if the variant can't produce a delta (history
592    /// truncated); the caller falls back to the full-state `crdt_to_wire`.
593    pub fn delta_since_bytes(&self, since: &VClock) -> Option<Vec<u8>> {
594        // bincode, NOT serde_json: a delta's `entries` is a map keyed by the ELEMENT (a `CrdtScalar`
595        // enum), and JSON cannot encode a non-string map key — bincode serializes maps as (key,value)
596        // sequences, so any key type round-trips.
597        fn tagged<D: serde::Serialize>(kind: u8, delta: &D) -> Option<Vec<u8>> {
598            let mut out = vec![kind];
599            out.extend(bincode::serialize(delta).ok()?);
600            Some(out)
601        }
602        let tag = self.crdt_kind().state_tag();
603        match self {
604            CrdtValue::Set(s) => tagged(tag, &s.delta_since(since)?),
605            CrdtValue::SetRemoveWins(s) => tagged(tag, &s.delta_since(since)?),
606            CrdtValue::Seq(s) => tagged(tag, &s.delta_since(since)?),
607            CrdtValue::Register(s) => tagged(tag, &s.delta_since(since)?),
608            // Counters ship full state as their delta (state-based, idempotent to merge).
609            CrdtValue::Counter(s) => tagged(tag, s),
610            CrdtValue::PnCounter(s) => tagged(tag, s),
611            CrdtValue::Map(s) => tagged(tag, &s.delta_since(since)?),
612        }
613    }
614
615    /// Apply a kind-tagged delta from `delta_since_bytes` of the SAME kind. Returns false on a
616    /// kind mismatch or malformed bytes, leaving self unchanged — a foreign / garbage delta never
617    /// corrupts the CRDT (the network-edge safety the `mergeable` receive needs).
618    pub fn apply_delta_bytes(&mut self, bytes: &[u8]) -> bool {
619        let Some((&kind, body)) = bytes.split_first() else {
620            return false;
621        };
622        if CrdtKind::from_state_tag(kind) != Some(self.crdt_kind()) {
623            return false;
624        }
625        match self {
626            CrdtValue::Set(s) => {
627                match bincode::deserialize::<<ORSet<CrdtScalar> as DeltaCrdt>::Delta>(body) {
628                    Ok(d) => {
629                        s.apply_delta(&d);
630                        true
631                    }
632                    Err(_) => false,
633                }
634            }
635            CrdtValue::SetRemoveWins(s) => {
636                match bincode::deserialize::<<ORSet<CrdtScalar, RemoveWins> as DeltaCrdt>::Delta>(
637                    body,
638                ) {
639                    Ok(d) => {
640                        s.apply_delta(&d);
641                        true
642                    }
643                    Err(_) => false,
644                }
645            }
646            CrdtValue::Seq(s) => {
647                match bincode::deserialize::<<RGA<CrdtScalar> as DeltaCrdt>::Delta>(body) {
648                    Ok(d) => {
649                        s.apply_delta(&d);
650                        true
651                    }
652                    Err(_) => false,
653                }
654            }
655            CrdtValue::Register(s) => {
656                match bincode::deserialize::<<MVRegister<CrdtScalar> as DeltaCrdt>::Delta>(body) {
657                    Ok(d) => {
658                        s.apply_delta(&d);
659                        true
660                    }
661                    Err(_) => false,
662                }
663            }
664            // Counter deltas are full states — deserialize and MERGE (per-replica max, idempotent).
665            CrdtValue::Counter(s) => match bincode::deserialize::<GCounter>(body) {
666                Ok(d) => {
667                    s.merge(&d);
668                    true
669                }
670                Err(_) => false,
671            },
672            CrdtValue::PnCounter(s) => match bincode::deserialize::<PNCounter>(body) {
673                Ok(d) => {
674                    s.merge(&d);
675                    true
676                }
677                Err(_) => false,
678            },
679            CrdtValue::Map(s) => {
680                match bincode::deserialize::<
681                    <ORMap<CrdtScalar, LatestWrite<CrdtScalar>> as DeltaCrdt>::Delta,
682                >(body)
683                {
684                    Ok(d) => {
685                        s.apply_delta(&d);
686                        true
687                    }
688                    Err(_) => false,
689                }
690            }
691        }
692    }
693
694    /// Serialize the WHOLE convergent state as a KIND-TAGGED payload — the state-based delta since
695    /// the empty clock (every variant produces a valid full state at `VClock::new()`). This is what
696    /// crosses a task/`Sync` boundary: the far side rebuilds a fresh replica and MERGES it, so
697    /// re-applying the same bytes is idempotent. Distinct from `crdt_to_wire` (which projects a
698    /// counter to a plain-Int relay form); this preserves the FULL per-replica CRDT state.
699    pub fn to_full_state_bytes(&self) -> Vec<u8> {
700        // Every variant yields `Some` at the empty clock (a full state is always producible), but a
701        // truncated-history variant could theoretically return `None`; degrade to an empty payload,
702        // which `from_full_state_bytes` reconstructs as a fresh (empty) replica.
703        self.delta_since_bytes(&VClock::new()).unwrap_or_default()
704    }
705
706    /// Reconstruct a CRDT from `to_full_state_bytes`: build a FRESH empty replica of the tagged kind,
707    /// then apply the state (a per-replica merge). A malformed / empty payload degrades to a fresh
708    /// grow-only counter (the safe default for the counter-`Sync` path). The fresh replica id keeps
709    /// the rebuilt value from aliasing the sender's live cell.
710    pub fn from_full_state_bytes(bytes: &[u8]) -> CrdtValue {
711        let kind = bytes
712            .first()
713            .and_then(|&t| CrdtKind::from_state_tag(t))
714            .unwrap_or(CrdtKind::Counter);
715        let mut cv = kind.fresh();
716        cv.apply_delta_bytes(bytes);
717        cv
718    }
719
720    /// `Show` rendering: a set renders in set notation `{…}` (matching a plain `Set`), a
721    /// sequence as an ordered list `[…]`, a register as its resolved value (or, while still
722    /// divergent, the brace-joined set of concurrent values).
723    pub fn render(&self) -> String {
724        let parts = || -> String {
725            self.to_runtime_vec()
726                .iter()
727                .map(render_runtime)
728                .collect::<Vec<_>>()
729                .join(", ")
730        };
731        match self {
732            CrdtValue::Register(_) => match self.register_value() {
733                Some(v) => render_runtime(&v),
734                None => format!("{{{}}}", parts()),
735            },
736            CrdtValue::Set(_) | CrdtValue::SetRemoveWins(_) => format!("{{{}}}", parts()),
737            CrdtValue::Seq(_) => format!("[{}]", parts()),
738            // A map renders like a `Map` — `{key: value, …}` — in key order.
739            CrdtValue::Map(m) => format!(
740                "{{{}}}",
741                m.sorted_entries()
742                    .into_iter()
743                    .map(|(k, v)| format!("{}: {}", k.render(), v.get().render()))
744                    .collect::<Vec<_>>()
745                    .join(", ")
746            ),
747            // A counter renders as its integer value — the same as the compiled tier's `Showable`.
748            CrdtValue::Counter(_) | CrdtValue::PnCounter(_) => {
749                self.counter_value().unwrap_or(0).to_string()
750            }
751        }
752    }
753}
754
755/// Structural equality used by the interpreter's `values_equal` for CRDT values: two
756/// CRDTs are equal when they observe the same elements (sequences also compare order).
757pub fn crdt_values_equal(a: &CrdtValue, b: &CrdtValue) -> bool {
758    match (a, b) {
759        (CrdtValue::Set(_), CrdtValue::Set(_))
760        | (CrdtValue::SetRemoveWins(_), CrdtValue::SetRemoveWins(_))
761        | (CrdtValue::Seq(_), CrdtValue::Seq(_))
762        | (CrdtValue::Register(_), CrdtValue::Register(_))
763        | (CrdtValue::Map(_), CrdtValue::Map(_)) => a.to_runtime_vec() == b.to_runtime_vec(),
764        // Two counters are equal when their integer values agree (internal per-replica slots differ).
765        (CrdtValue::Counter(_), CrdtValue::Counter(_))
766        | (CrdtValue::PnCounter(_), CrdtValue::PnCounter(_)) => {
767            a.counter_value() == b.counter_value()
768        }
769        _ => false,
770    }
771}
772
773/// Render a runtime scalar the way `Show` does for a CRDT element (text is unquoted).
774fn render_runtime(v: &RuntimeValue) -> String {
775    match v {
776        RuntimeValue::Int(n) => n.to_string(),
777        RuntimeValue::Text(s) => (**s).clone(),
778        RuntimeValue::Bool(b) => b.to_string(),
779        other => other.type_name().to_string(),
780    }
781}
782
783#[cfg(test)]
784#[path = "../../../logicaffeine_tests/unit/logicaffeine_compile/semantics/crdt/tests.rs"]
785mod tests;