Skip to main content

lean_ctx_cloud/capture/
emit.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Capture step 6 (SPEC-ENGINE §3.1.2): what the gate let through becomes
3//! signed `node.add` events in the place's replica — queued as pending (the
4//! offline queue the sync driver pushes), with the keyed dedupe key, the
5//! encrypted MinHash signature and an `own_sources` row, so a later run
6//! never sends the same claim twice and a purge can find the local text.
7
8use serde_json::json;
9
10use super::refs::Checkout;
11use super::{CapturedFact, dedupe};
12use crate::CloudError;
13use crate::events::build::{self, Place, Signer};
14use crate::events::hlc::{self, Stamp};
15use crate::replica::Replica;
16use lean_ctx::core::knowledge::NodeType;
17
18/// What [`emit`] queued.
19#[derive(Debug, Clone, Default, PartialEq, Eq)]
20pub struct Emitted {
21    /// `(event_id, node_id)` of every queued event.
22    pub queued: Vec<(String, String)>,
23    /// Claims the place already holds (exact key in the replica).
24    pub duplicates: usize,
25    /// Claims a purge removed (`purged_content`).
26    pub purged: usize,
27    /// `(event_id, to)` of every `derived_from` edge queued after its claim
28    /// (v5 2.2.2, [`super::derived`]).
29    pub derived: Vec<(String, String)>,
30    /// The clock after the last stamp.
31    pub clock: Stamp,
32}
33
34/// Where captured facts go: the place's replica, its key, the signer, and
35/// the checkout's name in `own_sources` (never shared).
36pub struct Target<'a> {
37    pub replica: &'a Replica,
38    pub place: &'a Place,
39    pub signer: &'a Signer<'a>,
40    pub project_hash: &'a str,
41    /// The Cloud answered C0 2.2: decisions carry their anchors.
42    pub decision_anchors: bool,
43    /// V9: keyed session refs, `None` unless the enrolled Cloud announced
44    /// `session_ref`: no event then carries a session.
45    pub sessions: Option<&'a crate::session_ref::SessionRefs>,
46}
47
48/// Queue a signed `node.add` per captured fact.
49pub fn emit(
50    target: &Target<'_>,
51    checkout: &mut Checkout,
52    facts: &[CapturedFact],
53    clock: Stamp,
54    now_ms: u64,
55) -> Result<Emitted, CloudError> {
56    let Target {
57        replica,
58        place,
59        signer,
60        project_hash,
61        decision_anchors,
62        sessions,
63    } = *target;
64    let mut out = Emitted {
65        clock,
66        ..Emitted::default()
67    };
68    for fact in facts {
69        let c = &fact.candidate;
70        let dk = dedupe::exact_key(&place.pk_id, c.node_type, &c.statement);
71        // A purged statement is never captured again (step 3c).
72        if replica.is_purged(&dk)? {
73            out.purged += 1;
74            continue;
75        }
76        if c.node_type != NodeType::Procedure && replica.dedupe_node(&dk)?.is_some() {
77            out.duplicates += 1;
78            continue;
79        }
80        // A fact names its subject (category, key) by a keyed reference, so
81        // another Instance's value for the same fact is found as a conflict
82        // (#286, [`super::conflicts`]); it takes the last `applies_to` slot.
83        let (applies, anchors) = if c.node_type == NodeType::Fact {
84            let (mut applies, anchors) =
85                build::applies_and_anchors_within(&fact.refs, checkout, build::MAX_APPLIES_TO - 1);
86            applies.push(super::conflicts::subject_ref(
87                &place.pk_id,
88                &fact.category,
89                &fact.key,
90            ));
91            (applies, anchors)
92        } else {
93            build::applies_and_anchors(&fact.refs, checkout)
94        };
95        let body = build::claim_body(c, &applies, anchors, decision_anchors)?;
96        out.clock = hlc::send(out.clock, now_ms);
97        let session = sessions.zip(fact.session.as_deref());
98        let session = session.and_then(|(refs, id)| refs.event_ref(id));
99        let (event, node_id) =
100            build::node_add_in(c, &body, place, out.clock, signer, session.as_deref())?;
101        let event_id = queue(replica, &event, out.clock)?;
102        replica.add_dedupe_key(&dk, &node_id)?;
103        replica.put_signature(&node_id, &dedupe::signature(&place.pk_id, &c.statement))?;
104        replica.put_own_source(
105            &node_id,
106            "fact",
107            &json!({
108                "project_hash": project_hash,
109                "category": fact.category,
110                "key": fact.key,
111                "value_digest": replica.value_digest(&fact.value),
112            }),
113        )?;
114        // Provenance: the edges follow their claim in the same push, only
115        // for nodes the body itself names (`node:<id>`, e.g. in
116        // `applies_to`), the usage reference the server counts (v5 2.6.1).
117        let cited = body.to_string();
118        for to in fact
119            .derived_from
120            .iter()
121            .filter(|to| cited.contains(&format!("node:{to}")))
122        {
123            out.clock = hlc::send(out.clock, now_ms);
124            let edge = build::edge_add_in(
125                "derived_from",
126                &node_id,
127                to,
128                c.evidence.as_str(),
129                place,
130                out.clock,
131                signer,
132                session.as_deref(),
133            )?;
134            out.derived
135                .push((queue(replica, &edge, out.clock)?, to.clone()));
136        }
137        out.queued.push((event_id, node_id));
138    }
139    Ok(out)
140}
141
142/// Queue a built event as pending; its event id.
143fn queue(replica: &Replica, event: &serde_json::Value, clock: Stamp) -> Result<String, CloudError> {
144    let event_id = event["event_id"]
145        .as_str()
146        .ok_or_else(|| CloudError::Local("built event without id".into()))?
147        .to_string();
148    let bytes = serde_json::to_vec(event).map_err(|e| CloudError::Local(e.to_string()))?;
149    replica.add_pending(&event_id, clock.wall_ms, clock.counter, None, &bytes)?;
150    Ok(event_id)
151}
152
153#[cfg(test)]
154mod tests {
155    use ed25519_dalek::SigningKey;
156
157    use super::*;
158    use crate::capture::CaptureCandidate;
159    use lean_ctx::core::knowledge::EvidenceLevel;
160    use lean_ctx::core::sensitivity::SensitivityLevel;
161
162    /// A session id as this engine generates it.
163    const SESSION: &str = "20261116-091500u123456p4242s0";
164
165    #[test]
166    fn captured_facts_queue_once_as_signed_events() {
167        let repo = crate::capture::tests::repo();
168        let data = tempfile::tempdir().unwrap();
169        let (replica, _) = Replica::open(data.path(), "pl_emit", &[3; 32]).unwrap();
170        let key = SigningKey::from_bytes(&[0x49; 32]);
171        let place = Place {
172            kind: "vault".into(),
173            id: "3f1c2b6a-8d4e-4a7b-9c10-5e2f6a7b8c01".into(),
174            pk_id: [9; 32],
175            causal_base: 0,
176        };
177        let signer = Signer {
178            key: &key,
179            hlc_node: "6f2b9c4e-1a3d-4e5f-8a7b-0c1d2e3f4a5b".into(),
180            worker_id: "wkr_vk4oelpv5lzjmev44hun".into(),
181        };
182        let fact = CapturedFact {
183            candidate: CaptureCandidate {
184                node_type: NodeType::Fact,
185                statement: "The relay drops frames when the link is slow.".into(),
186                steps: vec![],
187                commands: vec![],
188                refs: vec![],
189                evidence: EvidenceLevel::Observed,
190                sensitivity: SensitivityLevel::Public,
191            },
192            refs: vec!["file:src/lib.rs".into()],
193            category: "arch".into(),
194            key: "relay".into(),
195            value: "The relay drops frames when the link is slow.".into(),
196            derived_from: vec![],
197            // Learned in a session, but Cloud did not announce `session_ref`.
198            session: Some(SESSION.into()),
199        };
200        let mut checkout = Checkout::new(repo.path());
201        let start = Stamp {
202            wall_ms: 1_792_800_000_000,
203            counter: 0,
204        };
205        let target = Target {
206            replica: &replica,
207            place: &place,
208            signer: &signer,
209            project_hash: "ph",
210            decision_anchors: false,
211            sessions: None,
212        };
213        let first = emit(
214            &target,
215            &mut checkout,
216            std::slice::from_ref(&fact),
217            start,
218            1_792_800_000_000,
219        )
220        .unwrap();
221        assert_eq!(first.queued.len(), 1);
222        assert_eq!(
223            first.clock,
224            Stamp {
225                wall_ms: 1_792_800_000_000,
226                counter: 1
227            }
228        );
229        let pending = replica.pending().unwrap();
230        assert_eq!(pending.len(), 1);
231        let event: serde_json::Value = serde_json::from_slice(&pending[0].1).unwrap();
232        assert!(crate::events::sign::verify(
233            &event,
234            key.verifying_key().as_bytes()
235        ));
236        assert_eq!(event["body"]["anchors"][0]["ref"], "file:src/lib.rs");
237        assert!(
238            event.get("session_ref").is_none(),
239            "a Cloud without the feature hears no session"
240        );
241        // #286: the fact names its subject (category, key), keyed.
242        assert_eq!(
243            event["body"]["applies_to"],
244            serde_json::json!([
245                "file:src/lib.rs",
246                crate::capture::conflicts::subject_ref(&place.pk_id, "arch", "relay")
247            ])
248        );
249        let (kind, source) = replica.own_source(&first.queued[0].1).unwrap().unwrap();
250        assert_eq!(kind, "fact");
251        assert_ne!(
252            source["value_digest"],
253            fact.value.as_str(),
254            "only a keyed digest"
255        );
256
257        // The same claim again: already held, nothing queued.
258        let again = emit(
259            &target,
260            &mut checkout,
261            &[fact],
262            first.clock,
263            1_792_800_000_000,
264        )
265        .unwrap();
266        assert_eq!((again.queued.len(), again.duplicates), (0, 1));
267        assert_eq!(replica.pending().unwrap().len(), 1);
268    }
269
270    /// #286: two values of one fact (two Instances) carry the same subject
271    /// reference, which keeps its slot within the contract's five entries;
272    /// other node types carry none (their bodies have no `applies_to`).
273    #[test]
274    fn every_value_of_a_fact_names_the_same_subject_within_five_references() {
275        let repo = crate::capture::tests::repo();
276        let data = tempfile::tempdir().unwrap();
277        let (replica, _) = Replica::open(data.path(), "pl_subject", &[3; 32]).unwrap();
278        let key = SigningKey::from_bytes(&[0x49; 32]);
279        let place = Place {
280            kind: "vault".into(),
281            id: "3f1c2b6a-8d4e-4a7b-9c10-5e2f6a7b8c01".into(),
282            pk_id: [9; 32],
283            causal_base: 0,
284        };
285        let signer = Signer {
286            key: &key,
287            hlc_node: "6f2b9c4e-1a3d-4e5f-8a7b-0c1d2e3f4a5b".into(),
288            worker_id: "wkr_vk4oelpv5lzjmev44hun".into(),
289        };
290        let urls: Vec<String> = (0..6)
291            .map(|i| format!("https://docs.rs/blake3/{i}"))
292            .collect();
293        let fact = |node_type: NodeType, value: &str| CapturedFact {
294            candidate: CaptureCandidate {
295                node_type,
296                statement: value.into(),
297                steps: vec![],
298                commands: vec![],
299                refs: vec![],
300                evidence: EvidenceLevel::Observed,
301                sensitivity: SensitivityLevel::Public,
302            },
303            refs: urls.clone(),
304            category: "fact".into(),
305            key: "payments-retry".into(),
306            value: value.into(),
307            derived_from: vec![],
308            session: None,
309        };
310        let target = Target {
311            replica: &replica,
312            place: &place,
313            signer: &signer,
314            project_hash: "ph",
315            decision_anchors: false,
316            sessions: None,
317        };
318        let out = emit(
319            &target,
320            &mut Checkout::new(repo.path()),
321            &[
322                fact(NodeType::Fact, "Payments retry three times and then fail."),
323                fact(
324                    NodeType::Fact,
325                    "Payments back off for five minutes before any retry.",
326                ),
327                fact(
328                    NodeType::Gotcha,
329                    "Payments retries are not idempotent today.",
330                ),
331            ],
332            Stamp::default(),
333            1_792_800_000_000,
334        )
335        .unwrap();
336        assert_eq!(out.queued.len(), 3);
337        let bodies: Vec<serde_json::Value> = replica
338            .pending()
339            .unwrap()
340            .iter()
341            .map(|(_, b)| serde_json::from_slice::<serde_json::Value>(b).unwrap()["body"].clone())
342            .collect();
343        let subject = crate::capture::conflicts::subject_ref(&[9; 32], "fact", "payments-retry");
344        for body in &bodies[..2] {
345            let applies = body["applies_to"].as_array().unwrap();
346            assert_eq!(applies.len(), build::MAX_APPLIES_TO, "{body}");
347            assert_eq!(applies.last().unwrap(), subject.as_str());
348        }
349        assert!(bodies[2].get("applies_to").is_none(), "{}", bodies[2]);
350    }
351
352    /// v5 2.2.2, 2.6.1: a claim that names vault nodes is followed by one
353    /// signed `derived_from` edge per node its body cites, in the same push;
354    /// a node the body does not name gets no edge.
355    #[test]
356    fn a_derived_claim_queues_its_provenance_edges_after_the_node() {
357        let repo = crate::capture::tests::repo();
358        let data = tempfile::tempdir().unwrap();
359        let (replica, _) = Replica::open(data.path(), "pl_derive", &[3; 32]).unwrap();
360        let key = SigningKey::from_bytes(&[0x49; 32]);
361        let place = Place {
362            kind: "vault".into(),
363            id: "3f1c2b6a-8d4e-4a7b-9c10-5e2f6a7b8c01".into(),
364            pk_id: [9; 32],
365            causal_base: 4,
366        };
367        let signer = Signer {
368            key: &key,
369            hlc_node: "6f2b9c4e-1a3d-4e5f-8a7b-0c1d2e3f4a5b".into(),
370            worker_id: "wkr_vk4oelpv5lzjmev44hun".into(),
371        };
372        let statement = "The nightly export waits for advisory lock 42 before the ledger close.";
373        let fact = CapturedFact {
374            candidate: CaptureCandidate {
375                node_type: NodeType::Fact,
376                statement: statement.into(),
377                steps: vec![],
378                commands: vec![],
379                refs: vec![],
380                evidence: EvidenceLevel::Stated,
381                sensitivity: SensitivityLevel::Public,
382            },
383            refs: vec![
384                "file:src/lib.rs".into(),
385                "node:n_aaaaaaaaaaaaaaaaaaaaaacaa4".into(),
386            ],
387            category: "arch".into(),
388            key: "export".into(),
389            value: statement.into(),
390            derived_from: vec![
391                "n_aaaaaaaaaaaaaaaaaaaaaacaa4".into(),
392                "n_aaaaaaaaaaaaaaaaaaaaaacab4".into(),
393            ],
394            session: Some(SESSION.into()),
395        };
396        let refs = crate::session_ref::SessionRefs::from_key(
397            crate::receipts::ReceiptKey::from_bytes([5; 32]),
398        );
399        let target = Target {
400            replica: &replica,
401            place: &place,
402            signer: &signer,
403            project_hash: "ph",
404            decision_anchors: false,
405            sessions: Some(&refs),
406        };
407        let out = emit(
408            &target,
409            &mut Checkout::new(repo.path()),
410            &[fact],
411            Stamp::default(),
412            1_792_800_000_000,
413        )
414        .unwrap();
415        assert_eq!(out.queued.len(), 1);
416        let node_id = &out.queued[0].1;
417        assert_eq!(
418            out.derived
419                .iter()
420                .map(|(_, to)| to.as_str())
421                .collect::<Vec<_>>(),
422            ["n_aaaaaaaaaaaaaaaaaaaaaacaa4"],
423            "cab4 is not named in the body"
424        );
425        let pending: Vec<serde_json::Value> = replica
426            .pending()
427            .unwrap()
428            .iter()
429            .map(|(_, b)| serde_json::from_slice(b).unwrap())
430            .collect();
431        let ops: Vec<&str> = pending.iter().map(|e| e["op"].as_str().unwrap()).collect();
432        assert_eq!(ops, ["node.add", "edge.add"]);
433        // V9: the claim and its edges name the session it was learned in,
434        // keyed and inside the signature.
435        let session = refs.event_ref(SESSION).unwrap();
436        for event in &pending {
437            assert_eq!(event["session_ref"], session.as_str(), "{event}");
438            assert!(crate::events::sign::verify(
439                event,
440                key.verifying_key().as_bytes()
441            ));
442            let mut tampered = event.clone();
443            tampered["session_ref"] = "hs_00000000000000000000000000000000".into();
444            assert!(!crate::events::sign::verify(
445                &tampered,
446                key.verifying_key().as_bytes()
447            ));
448            assert!(!event.to_string().contains(SESSION));
449        }
450        // The usage reference the server checks: the claim body names it.
451        assert!(
452            pending[0]["body"]["applies_to"]
453                .as_array()
454                .unwrap()
455                .iter()
456                .any(|a| a == "node:n_aaaaaaaaaaaaaaaaaaaaaacaa4"),
457            "{}",
458            pending[0]["body"]
459        );
460        for (edge, to) in pending[1..].iter().zip(&out.derived) {
461            assert!(crate::events::sign::verify(
462                edge,
463                key.verifying_key().as_bytes()
464            ));
465            assert_eq!(edge["body"]["kind"], "derived_from");
466            assert_eq!(edge["body"]["from"], node_id.as_str());
467            assert_eq!(edge["body"]["to"], to.1.as_str());
468            assert_eq!(edge["provenance_claim"], "own");
469            assert_eq!(edge["capture"]["evidence"], "stated");
470            assert_eq!(edge["causal_base"], 4);
471            assert!(
472                edge["target"]
473                    .as_str()
474                    .is_some_and(|t| t.starts_with("e_") && t.len() == 28),
475                "{edge}"
476            );
477        }
478    }
479}