Skip to main content

khive_runtime/operations/
entity_keys.rs

1//! Caller keys on entities (ADR-221 section 1).
2//!
3//! A key names one live entity per `(namespace, kind, key)`. A keyed create
4//! writes when the key is free, answers the holder when the payload is the
5//! same, and refuses with `key_conflict` when it differs. Deleting an entity
6//! releases its keys; restoring it takes them all back or refuses.
7
8use std::collections::BTreeSet;
9
10use super::entity_create::EntityCreateWrite;
11use super::*;
12use khive_storage::EntityKeyHolder;
13
14/// The refusal text for a key over 512 UTF-8 bytes or holding U+0000.
15pub(crate) const ENTITY_KEY_REFUSAL: &str =
16    "key must be at most 512 UTF-8 bytes and must not contain U+0000";
17
18/// Claims lost to a concurrent writer before the create gives up. Each lost
19/// claim re-reads the holder, so a second loss needs the key to be released
20/// and taken again between two reads.
21const KEYED_CREATE_ATTEMPTS: usize = 3;
22
23/// Outcome of [`KhiveRuntime::create_keyed_entity_with_post_commit_report`].
24#[derive(Debug)]
25pub enum KeyedEntityCreate {
26    /// No live entity held the key: this call wrote `entity` and claimed the
27    /// key for it in the same transaction.
28    Created {
29        entity: Entity,
30        embedding: crate::retrieval::EmbeddingTruncationReport,
31        degradations: Vec<PostCommitDegradation>,
32    },
33    /// The live holder of the key carries the same payload. Nothing was
34    /// written.
35    Replayed { entity: Entity },
36    /// A live entity with a different payload holds the key. Nothing was
37    /// written; the holder is unchanged.
38    Conflict { existing_id: Uuid },
39}
40
41/// Outcome of [`KhiveRuntime::reload_keyed_entity`].
42#[derive(Debug)]
43pub enum KeyedEntityReload {
44    /// The holder now carries the request's payload.
45    Updated {
46        entity: Entity,
47        report: crate::curation::EntityUpdateReport,
48    },
49    /// The holder already carried the request's payload. Nothing was written.
50    Replayed { entity: Entity },
51    /// The key no longer names the entity the caller was cleared to update:
52    /// it was released, or another entity holds it now. Nothing was written.
53    Moved,
54}
55
56/// A fresh id for the row a keyed bulk create will write (ADR-221 section 1).
57///
58/// The bulk create names the id before it builds the row, so the update gate
59/// can judge a later item of the same request against that row. Only
60/// [`PendingEntityId::mint`] makes one and building the plan spends it, so one
61/// id names one new row.
62#[derive(Debug)]
63pub struct PendingEntityId(pub(super) Uuid);
64
65impl PendingEntityId {
66    /// A new random id.
67    pub fn mint() -> Self {
68        Self(Uuid::new_v4())
69    }
70
71    /// The id the row will carry.
72    pub fn id(&self) -> Uuid {
73        self.0
74    }
75}
76
77/// A plan that writes nothing and holds only while `holder` is still the
78/// live row it was read as: same id, `updated_at`, `deleted_at` and version.
79///
80/// A keyed bulk create that answers an item as an identical replay of a
81/// stored holder joins this to its unit (ADR-221 section 1), so the replay
82/// is judged inside the unit's transaction: a holder that changed after it
83/// was read rolls the unit back and the request is judged again.
84pub fn keyed_replay_assertion_plan(holder: &Entity) -> AtomicOpPlan {
85    crate::canonical_apply::unchanged_entity_assertion_plan(holder, "keyed-replay-assertion")
86}
87
88/// Whether `holder` carries the payload `spec` asks for, as a keyed create
89/// compares them.
90pub fn entity_carries_create_payload(holder: &Entity, spec: &EntityCreateSpec) -> bool {
91    same_entity_payload(
92        holder,
93        spec.entity_type.as_deref(),
94        &spec.name,
95        spec.description.as_deref(),
96        spec.properties.as_ref(),
97        &spec.tags,
98        &spec_aliases(spec),
99    )
100}
101
102/// The caller aliases a row written from `spec` holds: the requested ones
103/// other than its name.
104fn spec_aliases(spec: &EntityCreateSpec) -> BTreeSet<&str> {
105    spec.aliases
106        .iter()
107        .map(String::as_str)
108        .filter(|alias| *alias != spec.name)
109        .collect()
110}
111
112/// Whether two keyed create payloads are the same, as
113/// [`entity_carries_create_payload`] compares a holder with a request.
114pub fn same_create_payload(first: &EntityCreateSpec, second: &EntityCreateSpec) -> bool {
115    let mut held =
116        Entity::new("", &first.kind, &first.name).with_entity_type(first.entity_type.as_deref());
117    held.description = first.description.clone();
118    held.properties = first.properties.clone();
119    held.tags = first.tags.clone();
120    held.aliases = spec_aliases(first)
121        .into_iter()
122        .map(|alias| khive_storage::entity::EntityAlias {
123            alias: alias.to_owned(),
124            origin: khive_storage::entity::EntityAliasOrigin::Caller,
125        })
126        .collect();
127    entity_carries_create_payload(&held, second)
128}
129
130/// The caller property keys `holder` has and `wanted` leaves out: what a
131/// reload removes so the holder's caller properties become `wanted`.
132fn properties_to_remove(holder: &Entity, wanted: Option<&serde_json::Value>) -> Vec<String> {
133    match caller_properties(holder.properties.as_ref()) {
134        Some(serde_json::Value::Object(held)) => held
135            .keys()
136            .filter(|held_key| {
137                !wanted
138                    .and_then(serde_json::Value::as_object)
139                    .is_some_and(|asked| asked.contains_key(*held_key))
140            })
141            .cloned()
142            .collect(),
143        _ => Vec::new(),
144    }
145}
146
147/// The patch a reload writes: every caller field becomes the request's.
148fn reload_patch(
149    entity_type: Option<&str>,
150    name: &str,
151    description: Option<&str>,
152    wanted: Option<serde_json::Value>,
153    tags: &[String],
154) -> crate::EntityPatch {
155    crate::EntityPatch {
156        name: Some(name.to_owned()),
157        description: Some(description.map(str::to_owned)),
158        properties: wanted,
159        tags: Some(tags.to_vec()),
160        entity_type: Some(entity_type.map(str::to_owned)),
161    }
162}
163
164fn is_version_conflict(error: &RuntimeError) -> bool {
165    matches!(
166        error,
167        RuntimeError::Khive(error)
168            if error.details().and_then(|details| details.get("reason"))
169                == Some("version_conflict")
170    )
171}
172
173/// Validate a caller key and scan its exact bytes with the secret gate.
174///
175/// Runs before any holder lookup, so a refused key never reaches a read.
176pub(crate) fn validate_entity_key(key: &str) -> RuntimeResult<()> {
177    crate::note_validation::validate_key(key, ENTITY_KEY_REFUSAL)?;
178    crate::secret_gate::check_at(key, "entity", "key")
179}
180
181/// The caller-visible part of a properties value: the runtime-owned
182/// top-level keys removed, and `None` for an object left empty.
183fn caller_properties(properties: Option<&serde_json::Value>) -> Option<serde_json::Value> {
184    let value = properties?;
185    let serde_json::Value::Object(map) = value else {
186        return Some(value.clone());
187    };
188    let reserved = crate::secret_gate::RESERVED_PROPERTY_KEYS;
189    let kept: serde_json::Map<String, serde_json::Value> = map
190        .iter()
191        .filter(|(key, _)| !reserved.contains(&key.as_str()))
192        .map(|(key, value)| (key.clone(), value.clone()))
193        .collect();
194    (!kept.is_empty()).then_some(serde_json::Value::Object(kept))
195}
196
197/// Whether `holder` carries the payload a keyed create asked for: name,
198/// description, `entity_type`, typed-equal properties, tags as a set and
199/// caller-origin aliases as a set (ADR-221 section 1). `aliases` is the
200/// set the request asks for, its name already left out. A requested alias
201/// the holder holds under a rename or merge origin is left out of it too:
202/// the write keeps that row as it is, so the request would not store it.
203///
204/// Both sides' properties are read through [`caller_properties`]: the
205/// runtime-owned top-level keys are left out, because no caller can send
206/// them, and absent properties and `{}` compare equal on either side, so a
207/// holder created with `{}` and later stamped replays a request with `{}` or
208/// with none.
209fn same_entity_payload(
210    holder: &Entity,
211    entity_type: Option<&str>,
212    name: &str,
213    description: Option<&str>,
214    properties: Option<&serde_json::Value>,
215    tags: &[String],
216    aliases: &BTreeSet<&str>,
217) -> bool {
218    let stored: BTreeSet<&str> = aliases
219        .iter()
220        .copied()
221        .filter(|alias| {
222            !holder.aliases.iter().any(|held| {
223                held.alias == *alias
224                    && held.origin != khive_storage::entity::EntityAliasOrigin::Caller
225            })
226        })
227        .collect();
228    if super::entity_aliases::caller_alias_set(holder) != stored {
229        return false;
230    }
231    if holder.name != name
232        || holder.description.as_deref() != description
233        || holder.entity_type.as_deref() != entity_type
234    {
235        return false;
236    }
237    if caller_properties(holder.properties.as_ref()) != caller_properties(properties) {
238        return false;
239    }
240    let held: BTreeSet<&str> = holder.tags.iter().map(String::as_str).collect();
241    let asked: BTreeSet<&str> = tags.iter().map(String::as_str).collect();
242    held == asked
243}
244
245/// `key_conflict` for a keyed create whose key a different payload holds.
246///
247/// `existing_id` is named only when the caller may list the holder; the
248/// caller decides that and passes `None` otherwise.
249pub fn entity_key_conflict(key: &str, existing_id: Option<Uuid>) -> RuntimeError {
250    let mut details = vec![
251        ("reason", "key_conflict".to_string()),
252        ("key", key.to_owned()),
253    ];
254    if let Some(existing_id) = existing_id {
255        details.push(("existing_id", existing_id.to_string()));
256    }
257    KhiveError::conflict(format!(
258        "key_conflict: key {key:?} is already held by a live entity with a different payload"
259    ))
260    .with_details(khive_types::Details::new_owned(details))
261    .into()
262}
263
264/// `restore_key_conflict` naming every key another live entity took while
265/// entity `id` was deleted. The entity stays deleted.
266///
267/// A holder's id is named, in the message and in `taken_keys`, only for a
268/// kind `disclose` admits, as `key_conflict` names `existing_id` only where
269/// the caller may list the holder. The kind and key are always named.
270fn restore_entity_key_conflict(
271    id: Uuid,
272    taken: &[EntityKeyHolder],
273    disclose: &(dyn Fn(&str) -> bool + Sync),
274) -> RuntimeError {
275    let named: Vec<String> = taken
276        .iter()
277        .map(|taken| {
278            if disclose(&taken.kind) {
279                format!("{}:{:?} held by {}", taken.kind, taken.key, taken.holder_id)
280            } else {
281                format!("{}:{:?}", taken.kind, taken.key)
282            }
283        })
284        .collect();
285    let listed: Vec<serde_json::Value> = taken
286        .iter()
287        .map(|taken| {
288            let mut entry = serde_json::json!({"kind": taken.kind, "key": taken.key});
289            if disclose(&taken.kind) {
290                entry["existing_id"] = serde_json::json!(taken.holder_id.to_string());
291            }
292            entry
293        })
294        .collect();
295    KhiveError::conflict(format!(
296        "restore_key_conflict: entity {id} stays deleted; keys taken by live entities: {}",
297        named.join(", ")
298    ))
299    .with_details(khive_types::Details::new_owned([
300        ("reason", "restore_key_conflict".to_string()),
301        ("taken_keys", serde_json::Value::Array(listed).to_string()),
302    ]))
303    .into()
304}
305
306impl KhiveRuntime {
307    /// Create an entity under caller key `key`, unique per namespace and
308    /// base kind (ADR-221 section 1).
309    ///
310    /// The key is validated and secret-gated before any read. A free key is
311    /// claimed in the transaction that writes the entity. A held key answers
312    /// [`KeyedEntityCreate::Replayed`] when the holder carries the same
313    /// payload and [`KeyedEntityCreate::Conflict`] when it does not; neither
314    /// writes anything. `aliases` is part of the payload, compared as the set
315    /// of the holder's caller-origin aliases.
316    #[allow(clippy::too_many_arguments)]
317    pub async fn create_keyed_entity_with_post_commit_report(
318        &self,
319        token: &NamespaceToken,
320        kind: &str,
321        key: &str,
322        entity_type: Option<&str>,
323        name: &str,
324        description: Option<&str>,
325        properties: Option<serde_json::Value>,
326        tags: Vec<String>,
327        aliases: &EntityAliasChange,
328    ) -> RuntimeResult<KeyedEntityCreate> {
329        validate_entity_key(key)?;
330        self.validate_entity_kind(kind)?;
331        crate::secret_gate::reject_reserved_secret_gate_property(properties.as_ref())?;
332        let namespace = token.namespace().as_str();
333        let wanted_aliases = aliases.wanted(name);
334        for _ in 0..KEYED_CREATE_ATTEMPTS {
335            let holder = self
336                .entities(token)?
337                .get_entity_by_key(namespace, kind, key)
338                .await?;
339            if let Some(holder) = holder {
340                return Ok(
341                    if same_entity_payload(
342                        &holder,
343                        entity_type,
344                        name,
345                        description,
346                        properties.as_ref(),
347                        &tags,
348                        &wanted_aliases,
349                    ) {
350                        KeyedEntityCreate::Replayed { entity: holder }
351                    } else {
352                        KeyedEntityCreate::Conflict {
353                            existing_id: holder.id,
354                        }
355                    },
356                );
357            }
358            match self
359                .create_entity_with_embedding_report_inner(
360                    token,
361                    kind,
362                    entity_type,
363                    name,
364                    description,
365                    properties.clone(),
366                    tags.clone(),
367                    Vec::new(),
368                    Some(key),
369                    aliases,
370                )
371                .await?
372            {
373                EntityCreateWrite::Written(entity, embedding, degradations) => {
374                    return Ok(KeyedEntityCreate::Created {
375                        entity: *entity,
376                        embedding,
377                        degradations,
378                    });
379                }
380                EntityCreateWrite::KeyHeld => continue,
381            }
382        }
383        // Every claim lost to a concurrent writer: answer from the winner.
384        let holder = self
385            .entities(token)?
386            .get_entity_by_key(namespace, kind, key)
387            .await?;
388        match holder {
389            Some(holder)
390                if same_entity_payload(
391                    &holder,
392                    entity_type,
393                    name,
394                    description,
395                    properties.as_ref(),
396                    &tags,
397                    &wanted_aliases,
398                ) =>
399            {
400                Ok(KeyedEntityCreate::Replayed { entity: holder })
401            }
402            Some(holder) => Ok(KeyedEntityCreate::Conflict {
403                existing_id: holder.id,
404            }),
405            None => Err(RuntimeError::Internal(format!(
406                "keyed entity create: key {key:?} was claimed and released again during \
407                 {KEYED_CREATE_ATTEMPTS} claims"
408            ))),
409        }
410    }
411
412    /// A keyed create under `on_key: "update"` whose key `holder_id` holds
413    /// with a different payload (ADR-221 section 1).
414    ///
415    /// The holder's name, description, `entity_type`, tags and caller
416    /// properties become the request's: a field the request leaves out is
417    /// cleared, as the payload comparison reads it. The write is the
418    /// ordinary entity update, bound to the version this call compared, so a
419    /// holder that changed in between is read and compared again, and a
420    /// holder carrying a runtime-owned property key is refused as that
421    /// update refuses it: the key vouches for bytes this write would change.
422    /// The caller has already been cleared to update `holder_id`; if the key
423    /// no longer names it, nothing is written and the answer is
424    /// [`KeyedEntityReload::Moved`]. The holder's caller-origin aliases
425    /// become `aliases`; aliases a rename or a merge wrote stay.
426    #[allow(clippy::too_many_arguments)]
427    pub async fn reload_keyed_entity(
428        &self,
429        token: &NamespaceToken,
430        kind: &str,
431        key: &str,
432        holder_id: Uuid,
433        entity_type: Option<&str>,
434        name: &str,
435        description: Option<&str>,
436        properties: Option<serde_json::Value>,
437        tags: Vec<String>,
438        aliases: &EntityAliasChange,
439    ) -> RuntimeResult<KeyedEntityReload> {
440        validate_entity_key(key)?;
441        crate::secret_gate::reject_reserved_secret_gate_property(properties.as_ref())?;
442        let namespace = token.namespace().as_str();
443        let wanted = caller_properties(properties.as_ref());
444        let wanted_aliases = aliases.wanted(name);
445        for _ in 0..KEYED_CREATE_ATTEMPTS {
446            let holder = self
447                .entities(token)?
448                .get_entity_by_key(namespace, kind, key)
449                .await?;
450            let Some(holder) = holder.filter(|holder| holder.id == holder_id) else {
451                return Ok(KeyedEntityReload::Moved);
452            };
453            if same_entity_payload(
454                &holder,
455                entity_type,
456                name,
457                description,
458                wanted.as_ref(),
459                &tags,
460                &wanted_aliases,
461            ) {
462                return Ok(KeyedEntityReload::Replayed { entity: holder });
463            }
464            let removed = properties_to_remove(&holder, wanted.as_ref());
465            let removed: Vec<&str> = removed.iter().map(String::as_str).collect();
466            let patch = reload_patch(entity_type, name, description, wanted.clone(), &tags);
467            match self
468                .update_entity_with_removals_and_index_report(
469                    token,
470                    holder.id,
471                    patch,
472                    &removed,
473                    Some(holder.version),
474                    aliases,
475                )
476                .await
477            {
478                Ok((entity, report)) => {
479                    return Ok(KeyedEntityReload::Updated { entity, report });
480                }
481                Err(error) if is_version_conflict(&error) => continue,
482                Err(error) => return Err(error),
483            }
484        }
485        Err(RuntimeError::Internal(format!(
486            "keyed entity reload: the holder of key {key:?} changed during \
487             {KEYED_CREATE_ATTEMPTS} attempts"
488        )))
489    }
490
491    /// The update plan for a bulk item under `on_key: "update"` whose key
492    /// `holder` holds with a different payload (ADR-221 section 1).
493    ///
494    /// The holder's caller fields become `spec`'s, as
495    /// [`Self::reload_keyed_entity`] writes them, and the plan is bound to the
496    /// version `holder` carries, so a holder that changed after the caller
497    /// read it rolls the unit back. A holder carrying a runtime-owned
498    /// property key is refused as the ordinary update refuses it. The
499    /// returned record is the projection; its version is the one read.
500    pub async fn prepare_keyed_entity_reload_plan(
501        &self,
502        token: &NamespaceToken,
503        holder: &Entity,
504        spec: &EntityCreateSpec,
505    ) -> RuntimeResult<(Entity, AtomicOpPlan)> {
506        crate::secret_gate::reject_reserved_secret_gate_property(spec.properties.as_ref())?;
507        let aliases = EntityAliasChange::replace(&spec.aliases)?;
508        let wanted = caller_properties(spec.properties.as_ref());
509        let removed = properties_to_remove(holder, wanted.as_ref());
510        let removed: Vec<&str> = removed.iter().map(String::as_str).collect();
511        let patch = reload_patch(
512            spec.entity_type.as_deref(),
513            &spec.name,
514            spec.description.as_deref(),
515            wanted,
516            &spec.tags,
517        );
518        crate::atomic_prepare::prepare_keyed_reload_entity_record(
519            self,
520            token,
521            holder.id,
522            patch,
523            &removed,
524            holder.version,
525            &aliases,
526        )
527        .await
528    }
529
530    /// The live entity holding `key` for `kind` in the caller's primary
531    /// namespace, or `None` when no live entity holds it.
532    pub async fn get_entity_by_key(
533        &self,
534        token: &NamespaceToken,
535        kind: &str,
536        key: &str,
537    ) -> RuntimeResult<Option<Entity>> {
538        validate_entity_key(key)?;
539        Ok(self
540            .entities(token)?
541            .get_entity_by_key(token.namespace().as_str(), kind, key)
542            .await?)
543    }
544
545    /// Refuse a restore of entity `id` while another live entity holds any
546    /// key `id` released. `disclose` says, per kind, whether the refusal may
547    /// name the holder's id.
548    pub(super) async fn refuse_restore_over_taken_keys(
549        &self,
550        token: &NamespaceToken,
551        id: Uuid,
552        disclose: &(dyn Fn(&str) -> bool + Sync),
553    ) -> RuntimeResult<()> {
554        let taken = self.entities(token)?.taken_entity_keys(id).await?;
555        if taken.is_empty() {
556            Ok(())
557        } else {
558            Err(restore_entity_key_conflict(id, &taken, disclose))
559        }
560    }
561}
562
563#[cfg(test)]
564#[path = "entity_keys_tests.rs"]
565mod tests;