Skip to main content

lean_ctx_cloud/delivery/
knowledge_state.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Knowledge states (Cloud v5 CHECKLIST 2.2.1; C0 2.0
3//! `enums/knowledge-states.json`, `vectors/knowledge_state.vectors.json`):
4//! `verified | provisional | outdated | conflicting | rejected`, derived from
5//! the folded replica on every read, never stored. Cloud derives the same
6//! state from its projection, so the web and the agent see one answer.
7
8use std::collections::HashSet;
9
10use serde_json::Value;
11
12use crate::capture::conflicts::Kind;
13use crate::replica::fold::{Graph, Node};
14
15#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
16pub enum State {
17    Verified,
18    Provisional,
19    Outdated,
20    Conflicting,
21    Rejected,
22}
23
24impl State {
25    pub fn as_str(self) -> &'static str {
26        match self {
27            Self::Verified => "verified",
28            Self::Provisional => "provisional",
29            Self::Outdated => "outdated",
30            Self::Conflicting => "conflicting",
31            Self::Rejected => "rejected",
32        }
33    }
34
35    /// May an agent be given the node as current truth?
36    pub fn served_as_truth(self) -> bool {
37        matches!(self, Self::Verified | Self::Provisional)
38    }
39}
40
41/// The folded facts the state is derived from (the C0 vector inputs).
42#[derive(Debug, Clone, Default, PartialEq, Eq)]
43pub struct Inputs<'a> {
44    pub retracted: bool,
45    pub purged: bool,
46    pub evidence: Option<&'a str>,
47    /// A decision's `status`.
48    pub status: Option<&'a str>,
49    pub anchor_state: Option<&'a str>,
50    /// A live `supersedes` edge from a live node points at this one.
51    pub superseded: bool,
52    /// A live `contradicts` edge to a live node that is not superseded.
53    pub contradicted: bool,
54}
55
56/// `(state, reason)`; the reason is `None` only for `verified`.
57pub fn of_inputs(i: &Inputs<'_>) -> (State, Option<&'static str>) {
58    if i.retracted || i.purged {
59        return (State::Rejected, Some("retracted"));
60    }
61    if i.status == Some("reverted") {
62        return (State::Rejected, Some("reverted"));
63    }
64    if i.superseded || i.status == Some("superseded") {
65        return (State::Outdated, Some("superseded"));
66    }
67    match i.anchor_state {
68        Some("gone") => return (State::Outdated, Some("anchor_gone")),
69        Some("to_verify") => return (State::Outdated, Some("anchor_changed")),
70        _ => {}
71    }
72    if i.contradicted {
73        return (State::Conflicting, Some("contradicted"));
74    }
75    if i.evidence != Some("observed") {
76        return (State::Provisional, Some("not_observed"));
77    }
78    (State::Verified, None)
79}
80
81fn live(graph: &Graph, id: &str) -> bool {
82    graph
83        .nodes
84        .get(id)
85        .is_some_and(|n| !n.retracted && !n.purged)
86}
87
88/// The edge-derived inputs of every node, built once per graph (one pass
89/// over the edges, so delivery stays linear in the vault size).
90#[derive(Debug, Default)]
91pub struct Index {
92    /// Targets of a live `supersedes` edge from a live node.
93    superseded: HashSet<String>,
94    /// Ends of a live `contradicts` edge whose other end is live and not
95    /// superseded.
96    contradicted: HashSet<String>,
97}
98
99impl Index {
100    /// From the folded edges alone.
101    pub fn new(graph: &Graph) -> Self {
102        Self::build(graph, &[])
103    }
104
105    /// From the folded edges and the links of each fact's values the save
106    /// history resolves ([`crate::capture::conflicts::derived`]): two
107    /// Instances' concurrent values of one shared fact are `conflicting`
108    /// as soon as both are folded here, not only once the conflict edge has
109    /// travelled through the Cloud (#286).
110    pub fn with_saves(
111        graph: &Graph,
112        saves: &std::collections::BTreeMap<String, crate::replica::log::Save>,
113    ) -> Self {
114        Self::build(graph, &crate::capture::conflicts::derived(graph, saves))
115    }
116
117    fn build(graph: &Graph, links: &[(Kind, String, String)]) -> Self {
118        let mut superseded: HashSet<String> = graph
119            .edges
120            .values()
121            .filter(|e| e.kind == "supersedes" && !e.retracted && live(graph, &e.from))
122            .map(|e| e.to.clone())
123            .collect();
124        superseded.extend(
125            links
126                .iter()
127                .filter(|(kind, from, _)| *kind == Kind::Supersedes && live(graph, from))
128                .map(|(_, _, to)| to.clone()),
129        );
130        let open = |id: &str| live(graph, id) && !superseded.contains(id);
131        let mut contradicted = HashSet::new();
132        let pairs = graph
133            .edges
134            .values()
135            .filter(|e| e.kind == "contradicts" && !e.retracted)
136            .map(|e| (e.from.as_str(), e.to.as_str()))
137            .chain(
138                links
139                    .iter()
140                    .filter(|(kind, _, _)| *kind == Kind::Contradicts)
141                    .map(|(_, from, to)| (from.as_str(), to.as_str())),
142            );
143        for (from, to) in pairs {
144            if open(to) {
145                contradicted.insert(from.to_owned());
146            }
147            if open(from) {
148                contradicted.insert(to.to_owned());
149            }
150        }
151        Self {
152            superseded,
153            contradicted,
154        }
155    }
156
157    /// The state of `node_id` (`node` is its folded node).
158    pub fn state(&self, node_id: &str, node: &Node) -> (State, Option<&'static str>) {
159        let f = |k: &str| node.fields.get(k).and_then(Value::as_str);
160        of_inputs(&Inputs {
161            retracted: node.retracted,
162            purged: node.purged,
163            evidence: f("evidence"),
164            status: (node.node_type == "decision")
165                .then(|| f("status"))
166                .flatten(),
167            anchor_state: f("anchor_state"),
168            superseded: self.superseded.contains(node_id),
169            contradicted: self.contradicted.contains(node_id),
170        })
171    }
172}
173
174/// The state of one node of `graph` (builds the index; use [`Index`] for
175/// many nodes).
176pub fn of(graph: &Graph, node_id: &str, node: &Node) -> (State, Option<&'static str>) {
177    Index::new(graph).state(node_id, node)
178}
179
180#[cfg(test)]
181mod tests {
182    use serde_json::{Map, Value, json};
183
184    use super::*;
185    use crate::replica::fold::Edge;
186
187    const VECTORS: &str = include_str!(
188        "../../../../crates/lean-ctx-protocol/tests/fixtures/cloud-v2/vectors/knowledge_state.vectors.json"
189    );
190
191    #[test]
192    fn the_c0_knowledge_state_vectors_hold() {
193        let doc: Value = serde_json::from_str(VECTORS).unwrap();
194        let defaults = doc["defaults"].as_object().unwrap();
195        let mut seen = std::collections::BTreeSet::new();
196        for c in doc["cases"].as_array().unwrap() {
197            let name = c["name"].as_str().unwrap();
198            let mut m: Map<String, Value> = defaults.clone();
199            if let Some(Value::Object(set)) = c.get("set") {
200                for (k, v) in set {
201                    assert!(m.contains_key(k), "{name}: unknown input {k}");
202                    m.insert(k.clone(), v.clone());
203                }
204            }
205            let b = |k: &str| m[k].as_bool().unwrap();
206            let (state, reason) = of_inputs(&Inputs {
207                retracted: b("retracted"),
208                purged: b("purged"),
209                evidence: m["evidence"].as_str(),
210                status: m["status"].as_str(),
211                anchor_state: m["anchor_state"].as_str(),
212                superseded: b("superseded"),
213                contradicted: b("contradicted"),
214            });
215            assert_eq!(state.as_str(), c["state"], "{name}");
216            assert_eq!(
217                reason.map_or(Value::Null, Value::from),
218                c["reason"],
219                "{name}"
220            );
221            seen.insert(state);
222        }
223        assert_eq!(seen.len(), 5, "a case per state");
224    }
225
226    fn node(fields: &Value) -> Node {
227        Node {
228            node_type: "fact".into(),
229            fields: fields.as_object().cloned().unwrap(),
230            ..Node::default()
231        }
232    }
233
234    fn edge(kind: &str, from: &str, to: &str) -> Edge {
235        Edge {
236            kind: kind.into(),
237            from: from.into(),
238            to: to.into(),
239            ..Edge::default()
240        }
241    }
242
243    #[test]
244    fn the_graph_inputs_follow_live_edges() {
245        let mut g = Graph::default();
246        for id in ["n_a", "n_b", "n_c"] {
247            g.nodes.insert(
248                id.into(),
249                node(&json!({"statement": id, "evidence": "observed"})),
250            );
251        }
252        let state = |g: &Graph, id: &str| of(g, id, &g.nodes[id]).0;
253        assert_eq!(state(&g, "n_a"), State::Verified);
254        g.edges
255            .insert("e_1".into(), edge("contradicts", "n_a", "n_b"));
256        assert_eq!(state(&g, "n_a"), State::Conflicting);
257        assert_eq!(state(&g, "n_b"), State::Conflicting);
258        // c supersedes b: b is outdated, the contradiction with it is moot.
259        g.edges
260            .insert("e_2".into(), edge("supersedes", "n_c", "n_b"));
261        assert_eq!(state(&g, "n_b"), State::Outdated);
262        assert_eq!(state(&g, "n_a"), State::Verified);
263        // A retracted successor supersedes nothing.
264        g.nodes.get_mut("n_c").unwrap().retracted = true;
265        assert_eq!(state(&g, "n_b"), State::Conflicting);
266        // The anchor re-check makes a claim outdated, `fresh` clears it.
267        g.nodes
268            .get_mut("n_a")
269            .unwrap()
270            .fields
271            .insert("anchor_state".into(), json!("to_verify"));
272        assert_eq!(
273            of(&g, "n_a", &g.nodes["n_a"]),
274            (State::Outdated, Some("anchor_changed"))
275        );
276        g.nodes
277            .get_mut("n_a")
278            .unwrap()
279            .fields
280            .insert("anchor_state".into(), json!("fresh"));
281        assert_eq!(state(&g, "n_a"), State::Conflicting);
282    }
283
284    /// Retrieval never serves outdated, conflicting or rejected knowledge
285    /// as current truth: rejected and superseded leave delivery, the rest
286    /// come last with a label.
287    #[test]
288    fn delivery_marks_or_drops_what_is_not_current_truth() {
289        use crate::delivery::{Bucket, items, render};
290        let mut g = Graph::default();
291        let mut add = |id: &str, statement: &str, extra: Value| {
292            let mut f = json!({"statement": statement, "evidence": "observed"});
293            for (k, v) in extra.as_object().unwrap() {
294                f[k] = v.clone();
295            }
296            let mut n = node(&f);
297            n.provenance = Some("workspace".into());
298            g.nodes.insert(id.into(), n);
299        };
300        add("n_ok", "Retries back off with jitter.", json!({}));
301        add("n_old", "Retries use a fixed delay.", json!({}));
302        add("n_new", "Retries back off with full jitter.", json!({}));
303        add(
304            "n_moved",
305            "The retry cap lives in retry.rs.",
306            json!({"anchor_state": "to_verify"}),
307        );
308        add("n_x", "Retries are unlimited.", json!({}));
309        add("n_y", "Retries stop after five tries.", json!({}));
310        g.edges
311            .insert("e_s".into(), edge("supersedes", "n_new", "n_old"));
312        g.edges
313            .insert("e_c".into(), edge("contradicts", "n_x", "n_y"));
314        let no_trust = |_: &str| -> Option<String> { None };
315        let list = items(&g, &no_trust, "");
316        let got: Vec<(&str, Bucket)> = list
317            .iter()
318            .map(|i| (i.node_id.as_str(), i.bucket))
319            .collect();
320        assert_eq!(
321            got,
322            vec![
323                ("n_new", Bucket::Normal),
324                ("n_ok", Bucket::Normal),
325                ("n_moved", Bucket::Outdated),
326                ("n_x", Bucket::Conflicting),
327                ("n_y", Bucket::Conflicting),
328            ]
329        );
330        let out = render("acme/billing", &list, 1_500);
331        assert!(
332            !out.contains("fixed delay"),
333            "superseded is not delivered: {out}"
334        );
335        assert!(out.contains("[outdated: re-verify] fact"), "{out}");
336        assert_eq!(out.matches("[conflicting] fact").count(), 2, "{out}");
337        assert_eq!(
338            out,
339            render("acme/billing", &items(&g, &no_trust, ""), 1_500)
340        );
341    }
342}