Skip to main content

khive_runtime/
keyed_message.rs

1//! A message pair claims its caller key before any extra statement of the unit runs.
2//!
3//! The claim decides a duplicate-key race, so a competing pair loses at the claim and replays the
4//! existing holder instead of failing at a later row.
5
6use khive_storage::{Note, SqlStatement, SqlValue};
7use khive_types::{Details, KhiveError};
8use uuid::Uuid;
9
10use crate::atomic_message::{prepare_atomic_notes, AtomicNoteOptions, AtomicNoteSpec};
11use crate::atomic_plan::{AffectedRowGuard, PlanStatement};
12use crate::atomic_runner::{run_atomic_unit, AtomicOpFailure, AtomicOpPlan, AtomicRunOutcome};
13use crate::{KhiveRuntime, RuntimeError, RuntimeResult};
14
15const KEY_CLAIM: &str = "message-key-claim";
16
17pub enum KeyedMessageWrite {
18    Created {
19        notes: Vec<Note>,
20        embedding_truncation: crate::retrieval::EmbeddingTruncationReport,
21    },
22    Existing(Uuid),
23}
24
25/// Create exactly two caller-namespaced message notes or return the outbound
26/// holder after rolling back a competing pair. The comm layer verifies payload
27/// and sibling integrity before treating `Existing` as a successful replay.
28pub async fn create_keyed_message_pair(
29    runtime: &KhiveRuntime,
30    specs: [AtomicNoteSpec<'_>; 2],
31    physical_key: &str,
32) -> RuntimeResult<KeyedMessageWrite> {
33    create_keyed_message_pair_with_attachments(runtime, specs, physical_key, &[]).await
34}
35
36/// Include every copy's attachments in the same unit, ahead of the key claim.
37pub async fn create_keyed_message_pair_with_attachments(
38    runtime: &KhiveRuntime,
39    specs: [AtomicNoteSpec<'_>; 2],
40    physical_key: &str,
41    attachments: &[khive_storage::NewAttachment],
42) -> RuntimeResult<KeyedMessageWrite> {
43    create_keyed_message_pair_with_extra_statements(
44        runtime,
45        specs,
46        physical_key,
47        attachments,
48        Vec::new(),
49    )
50    .await
51}
52
53/// Like [`create_keyed_message_pair_with_attachments`], and also commit `extra_statements` in the
54/// same unit, after the attachments and after the key claim. The claim is the only statement that
55/// decides a duplicate-key race: a competing pair loses there, before any extra row is written,
56/// and the existing holder is returned. A winning pair commits the claim, the notes, the
57/// attachments and the extra rows together.
58pub async fn create_keyed_message_pair_with_extra_statements(
59    runtime: &KhiveRuntime,
60    specs: [AtomicNoteSpec<'_>; 2],
61    physical_key: &str,
62    attachments: &[khive_storage::NewAttachment],
63    extra_statements: Vec<SqlStatement>,
64) -> RuntimeResult<KeyedMessageWrite> {
65    crate::atomic_message::validate_note_attachments(runtime, attachments)?;
66    let namespace = specs[0].token.namespace().as_str().to_owned();
67    if specs.iter().any(|spec| spec.kind != "message")
68        || specs[1].token.namespace().as_str() != namespace
69        || specs[0].token.actor().id != specs[1].token.actor().id
70        || specs[0].id.is_none()
71        || specs[1].id.is_none()
72        || specs[0].id == specs[1].id
73    {
74        return Err(RuntimeError::InvalidInput(
75            "a keyed message pair requires distinct IDs in one actor namespace".into(),
76        ));
77    }
78    let mut prepared =
79        prepare_atomic_notes(runtime, specs.into(), AtomicNoteOptions::default()).await?;
80    crate::atomic_message::append_note_attachments(&mut prepared, attachments)?;
81    for note in &prepared.notes {
82        crate::secret_gate::reject_reserved_secret_gate_property(note.properties.as_ref())?;
83    }
84    let outbound_id = prepared.notes[0].id;
85    for (plan, note) in prepared.plans.iter_mut().zip(&prepared.notes) {
86        let AtomicOpPlan::AddNote(plan) = plan else {
87            return Err(RuntimeError::Internal(
88                "expected prepared message note".into(),
89            ));
90        };
91        // A caller-supplied UUID must never turn pair creation into an upsert.
92        plan.statements[0].statement =
93            khive_db::stores::note::note_insert_if_absent_statement(note);
94    }
95    let Some(AtomicOpPlan::AddNote(last)) = prepared.plans.last_mut() else {
96        return Err(RuntimeError::Internal(
97            "expected recipient message plan".into(),
98        ));
99    };
100    last.statements.push(PlanStatement {
101        statement: SqlStatement {
102            sql: "UPDATE OR IGNORE notes SET key = ?1 WHERE id = ?2 AND namespace = ?3 \
103                  AND kind = 'message' AND key IS NULL AND deleted_at IS NULL"
104                .into(),
105            params: vec![
106                SqlValue::Text(physical_key.to_owned()),
107                SqlValue::Text(outbound_id.to_string()),
108                SqlValue::Text(namespace.clone()),
109            ],
110            label: Some(KEY_CLAIM.into()),
111        },
112        guard: Some(AffectedRowGuard::exactly(1)),
113    });
114    // The claim is the only statement that decides a duplicate-key race, so it runs before the
115    // extra statements. A competing pair then rolls back here and replays the existing holder;
116    // were an extra row (for example a transport row keyed by the same logical id) placed first,
117    // the loser would fail on that row and surface as an internal error instead of a replay.
118    crate::atomic_message::append_extra_statements(&mut prepared, extra_statements)?;
119
120    match run_atomic_unit(runtime.sql().as_ref(), prepared.plans).await {
121        Ok(AtomicRunOutcome::Committed { .. }) => {
122            prepared.notes[0].key = Some(physical_key.to_owned());
123            Ok(KeyedMessageWrite::Created {
124                notes: prepared.notes,
125                embedding_truncation: prepared.embedding_truncation,
126            })
127        }
128        Ok(AtomicRunOutcome::RolledBack {
129            failure:
130                AtomicOpFailure::GuardFailed {
131                    statement_label,
132                    observed: 0,
133                    ..
134                },
135            ..
136        }) if statement_label.as_deref() == Some(KEY_CLAIM) => {
137            find_keyed_message_holder(runtime, &namespace, physical_key)
138                .await?
139                .map(KeyedMessageWrite::Existing)
140                .ok_or_else(|| {
141                    KhiveError::unavailable("message key holder disappeared during reconciliation")
142                        .with_details(Details::new_owned([(
143                            "reason",
144                            "key_holder_unresolved".into(),
145                        )]))
146                        .into()
147                })
148        }
149        Ok(AtomicRunOutcome::RolledBack {
150            failed_op_index,
151            failure,
152        }) => Err(RuntimeError::Internal(format!(
153            "atomic message pair rolled back at op {failed_op_index}: {failure:?}"
154        ))),
155        Err(error) => Err(RuntimeError::Storage(error.0)),
156    }
157}
158
159/// Look up the live outbound holder without preparing or attempting a write.
160/// The comm layer must validate the request and intact pair before returning it.
161pub async fn find_keyed_message_holder(
162    runtime: &KhiveRuntime,
163    namespace: &str,
164    physical_key: &str,
165) -> RuntimeResult<Option<Uuid>> {
166    let holder = runtime
167        .sql()
168        .reader()
169        .await?
170        .query_scalar(SqlStatement {
171            sql: "SELECT id FROM notes WHERE namespace = ?1 AND kind = 'message' \
172              AND key = ?2 AND deleted_at IS NULL LIMIT 1"
173                .into(),
174            params: vec![
175                SqlValue::Text(namespace.to_owned()),
176                SqlValue::Text(physical_key.to_owned()),
177            ],
178            label: Some("message-key-holder".into()),
179        })
180        .await?;
181    match holder {
182        Some(SqlValue::Text(id)) => Uuid::parse_str(&id)
183            .map(Some)
184            .map_err(|error| RuntimeError::Internal(format!("invalid message holder id: {error}"))),
185        None => Ok(None),
186        Some(_) => Err(RuntimeError::Internal(
187            "message holder id is not text".into(),
188        )),
189    }
190}