Skip to main content

khive_changeset/
invert.rs

1//! Pure, stage-time inversion against caller-supplied current records.
2
3use std::collections::{BTreeMap, BTreeSet};
4
5use khive_types::{EntityAlias, EntityAliasOrigin, Id128, Link, Note, NoteStatus};
6
7use crate::record::same_set;
8use crate::{
9    ChangeSet, CreateOp, CreateTarget, DeleteOp, DeletePreimage, EdgePatch, EdgePreimage,
10    EntityPatch, EntityPreimage, EntityRecord, Envelope, LinkOp, NotePatch, NotePreimage, Op,
11    RestoreOp, UpdateOp, UpdatePatch, UpdatePreimage,
12};
13
14/// Current records, including soft-deleted records, read when staging a revert.
15///
16/// Each key must equal its record's identifier. The caller supplies records in
17/// the same field representation as the staged operations; inversion does not
18/// normalize properties, tags, namespaces, or default values. Ordered maps keep
19/// this input deterministic on native and wasm32 targets.
20///
21/// See `crates/khive-changeset/docs/api/invert.md` for caller responsibilities.
22#[derive(Clone, Debug, Default)]
23pub struct CurrentState {
24    /// Current entity records with their keys and aliases, keyed by their
25    /// header identifiers.
26    pub entities: BTreeMap<Id128, EntityRecord>,
27    /// Current note records, keyed by their header identifiers.
28    pub notes: BTreeMap<Id128, Note>,
29    /// Current edge records, keyed by their edge identifiers.
30    pub edges: BTreeMap<Id128, Link>,
31}
32
33/// A refusal to stage an inverse; no partially inverted change-set is returned.
34///
35/// Operation indexes are zero-based indexes in the original forward op-list.
36#[derive(Debug, thiserror::Error)]
37pub enum InvertError {
38    /// A revert must have its own provenance rather than reuse the forward envelope.
39    #[error("the inverse envelope must differ from the forward envelope")]
40    ReusedEnvelope,
41    /// This format cannot yet represent the exact inverse of this operation.
42    #[error("operation {index} ({op}) is not invertible")]
43    NotInvertible {
44        /// Original forward operation index.
45        index: usize,
46        /// Forward operation name.
47        op: &'static str,
48    },
49    /// The caller did not supply the target record in the required substrate map.
50    #[error("operation {index} is missing current record {id}")]
51    MissingCurrent {
52        /// Original forward operation index.
53        index: usize,
54        /// Identifier of the required current record.
55        id: Id128,
56    },
57    /// The working record no longer matches a field required by the forward operation.
58    #[error("operation {index} record {id} differs in field {field}")]
59    Invalidated {
60        /// Original forward operation index.
61        index: usize,
62        /// Identifier of the affected record.
63        id: Id128,
64        /// Mismatched field name; `id` also names map-key/record-ID mismatches.
65        field: &'static str,
66    },
67    /// The captured delete preimage cannot describe a valid live restored record.
68    #[error("operation {index} inverse restore is invalid: {reason}")]
69    InverseRestore {
70        /// Original forward operation index.
71        index: usize,
72        /// The checked restore constructor's diagnostic.
73        reason: String,
74    },
75    /// The existing checked update constructor refused the swapped patch/preimage.
76    #[error("operation {index} inverse update is invalid: {reason}")]
77    InverseUpdate {
78        /// Original forward operation index.
79        index: usize,
80        /// The checked constructor's diagnostic.
81        reason: String,
82    },
83}
84
85impl ChangeSet {
86    /// Produces a reverse-ordered inverse with the caller's fresh envelope.
87    ///
88    /// Current records are checked and rewound in a private working copy, so
89    /// repeated updates compare against the correct intermediate values. An
90    /// update checks only fields it touches. A create or link must still match
91    /// its staged fields and be live; its inverse is a soft delete carrying the
92    /// supplied full record, including its actual timestamps.
93    ///
94    /// This is a pure stage-time check, not an atomic comparison at landing.
95    /// The caller reads current records and supplies the revert's provenance.
96    /// Neither this change-set nor `current` is modified, even on refusal.
97    ///
98    /// # Errors
99    ///
100    /// Refuses a reused envelope, hard deletes/merges, missing or invalidated
101    /// current records, an unrestorable delete preimage, or an invalid swapped update.
102    pub fn invert(
103        &self,
104        envelope: Envelope,
105        current: &CurrentState,
106    ) -> Result<ChangeSet, InvertError> {
107        if envelope == self.envelope {
108            return Err(InvertError::ReusedEnvelope);
109        }
110        let mut working = current.clone();
111        // Restore records do not capture the earlier tombstone timestamp. Track
112        // rewound lifecycle state separately instead of fabricating a timestamp.
113        let mut tombstones = BTreeSet::new();
114        let mut ops = Vec::with_capacity(self.ops.len());
115        for (index, op) in self.ops.iter().enumerate().rev() {
116            let inverse = match op {
117                Op::Create(create) => {
118                    let substrate = match &create.target {
119                        CreateTarget::Entity(_) => 0,
120                        CreateTarget::Note(_) => 1,
121                    };
122                    check(
123                        index,
124                        create.id,
125                        "deleted_at",
126                        !tombstones.contains(&(substrate, create.id)),
127                    )?;
128                    invert_create(index, create, &mut working)?
129                }
130                Op::Link(link) => {
131                    check(
132                        index,
133                        link.id,
134                        "deleted_at",
135                        !tombstones.contains(&(2, link.id)),
136                    )?;
137                    invert_link(index, link, &mut working)?
138                }
139                Op::Update(update) => invert_update(index, update, &mut working)?,
140                Op::Delete(delete) if delete.hard => {
141                    return Err(InvertError::NotInvertible {
142                        index,
143                        op: "delete",
144                    });
145                }
146                Op::Delete(delete) => invert_delete(index, delete, &mut working, &mut tombstones)?,
147                Op::Restore(restore) => {
148                    invert_restore(index, restore, &mut working, &mut tombstones)?
149                }
150                Op::Merge(_) => {
151                    return Err(InvertError::NotInvertible { index, op: "merge" });
152                }
153            };
154            ops.push(inverse);
155        }
156        Ok(ChangeSet::new(envelope, ops))
157    }
158}
159
160fn check(index: usize, id: Id128, field: &'static str, matches: bool) -> Result<(), InvertError> {
161    if matches {
162        Ok(())
163    } else {
164        Err(InvertError::Invalidated { index, id, field })
165    }
166}
167
168type RecordKey = (u8, Id128);
169
170fn record_key(record: &DeletePreimage) -> RecordKey {
171    match record {
172        DeletePreimage::Entity(row) => (0, row.entity.header.id),
173        DeletePreimage::Note(row) => (1, row.header.id),
174        DeletePreimage::Edge(row) => (2, row.id),
175    }
176}
177
178fn is_deleted(record: &DeletePreimage) -> bool {
179    match record {
180        DeletePreimage::Entity(row) => row.entity.deleted_at.is_some(),
181        DeletePreimage::Note(row) => row.deleted_at.is_some(),
182        DeletePreimage::Edge(row) => row.deleted_at.is_some(),
183    }
184}
185
186fn current_record(
187    index: usize,
188    id: Id128,
189    expected: &DeletePreimage,
190    working: &CurrentState,
191) -> Result<DeletePreimage, InvertError> {
192    let record = match expected {
193        DeletePreimage::Entity(_) => working
194            .entities
195            .get(&id)
196            .cloned()
197            .map(Box::new)
198            .map(DeletePreimage::Entity),
199        DeletePreimage::Note(_) => working
200            .notes
201            .get(&id)
202            .cloned()
203            .map(Box::new)
204            .map(DeletePreimage::Note),
205        DeletePreimage::Edge(_) => working
206            .edges
207            .get(&id)
208            .cloned()
209            .map(Box::new)
210            .map(DeletePreimage::Edge),
211    }
212    .ok_or(InvertError::MissingCurrent { index, id })?;
213    check(index, id, "id", record_key(&record).1 == id)?;
214    Ok(record)
215}
216
217fn rewind_record(record: &DeletePreimage, working: &mut CurrentState) {
218    match record {
219        DeletePreimage::Entity(row) => {
220            working.entities.insert(row.entity.header.id, *row.clone());
221        }
222        DeletePreimage::Note(row) => {
223            working.notes.insert(row.header.id, *row.clone());
224        }
225        DeletePreimage::Edge(row) => {
226            working.edges.insert(row.id, *row.clone());
227        }
228    }
229}
230
231fn check_record_content(
232    index: usize,
233    id: Id128,
234    current: &DeletePreimage,
235    expected: &DeletePreimage,
236) -> Result<(), InvertError> {
237    macro_rules! fields {
238        ($current:ident, $expected:ident, $($field:ident),+ $(,)?) => {
239            $(check(index, id, stringify!($field), $current.$field == $expected.$field)?;)+
240        };
241    }
242    match (current, expected) {
243        (DeletePreimage::Entity(record), DeletePreimage::Entity(prior_record)) => {
244            let (row, prior) = (&record.entity, &prior_record.entity);
245            fields!(
246                row,
247                prior,
248                kind,
249                entity_type,
250                name,
251                description,
252                properties,
253                tags
254            );
255            check(
256                index,
257                id,
258                "namespace",
259                row.header.namespace == prior.header.namespace,
260            )?;
261            check(
262                index,
263                id,
264                "created_at",
265                row.header.created_at == prior.header.created_at,
266            )?;
267            check(
268                index,
269                id,
270                "keys",
271                same_set(&record.keys, &prior_record.keys),
272            )?;
273            check(
274                index,
275                id,
276                "aliases",
277                same_set(&record.aliases, &prior_record.aliases),
278            )?;
279        }
280        (DeletePreimage::Note(row), DeletePreimage::Note(prior)) => {
281            fields!(
282                row,
283                prior,
284                kind,
285                status,
286                content,
287                properties,
288                tags,
289                salience,
290                decay_factor,
291                expires_at
292            );
293            check(
294                index,
295                id,
296                "namespace",
297                row.header.namespace == prior.header.namespace,
298            )?;
299            check(
300                index,
301                id,
302                "created_at",
303                row.header.created_at == prior.header.created_at,
304            )?;
305        }
306        (DeletePreimage::Edge(row), DeletePreimage::Edge(prior)) => {
307            fields!(
308                row, prior, namespace, source, target, relation, weight, properties, created_at
309            );
310        }
311        _ => check(index, id, "substrate", false)?,
312    }
313    Ok(())
314}
315
316fn invert_delete(
317    index: usize,
318    delete: &DeleteOp,
319    working: &mut CurrentState,
320    tombstones: &mut BTreeSet<RecordKey>,
321) -> Result<Op, InvertError> {
322    let id = delete.target_id;
323    let restore = RestoreOp::new(id, delete.preimage.clone())
324        .map_err(|reason| InvertError::InverseRestore { index, reason })?;
325    let mut current = current_record(index, id, &delete.preimage, working)?;
326    let key = record_key(&delete.preimage);
327    check(
328        index,
329        id,
330        "deleted_at",
331        is_deleted(&current) || tombstones.contains(&key),
332    )?;
333    if !tombstones.contains(&key) {
334        match (&mut current, &delete.preimage) {
335            (DeletePreimage::Entity(row), DeletePreimage::Entity(prior)) => {
336                check(
337                    index,
338                    id,
339                    "updated_at",
340                    row.entity.header.updated_at == prior.entity.header.updated_at,
341                )?;
342            }
343            (DeletePreimage::Note(row), DeletePreimage::Note(prior)) => {
344                check(
345                    index,
346                    id,
347                    "updated_at",
348                    row.header.updated_at == prior.header.updated_at,
349                )?;
350                check(index, id, "status", row.status == NoteStatus::Deleted)?;
351                row.status = prior.status;
352            }
353            _ => {}
354        }
355    }
356    check_record_content(index, id, &current, &delete.preimage)?;
357    rewind_record(&delete.preimage, working);
358    tombstones.remove(&key);
359    Ok(Op::Restore(restore))
360}
361
362fn invert_restore(
363    index: usize,
364    restore: &RestoreOp,
365    working: &mut CurrentState,
366    tombstones: &mut BTreeSet<RecordKey>,
367) -> Result<Op, InvertError> {
368    let id = restore.target_id();
369    let key = record_key(restore.record());
370    let current = current_record(index, id, restore.record(), working)?;
371    check(
372        index,
373        id,
374        "deleted_at",
375        !is_deleted(&current) && !tombstones.contains(&key),
376    )?;
377    check_record_content(index, id, &current, restore.record())?;
378    tombstones.insert(key);
379    Ok(Op::Delete(DeleteOp {
380        target_id: id,
381        hard: false,
382        preimage: current,
383    }))
384}
385
386fn invert_create(
387    index: usize,
388    create: &CreateOp,
389    working: &mut CurrentState,
390) -> Result<Op, InvertError> {
391    let id = create.id;
392    let preimage = match &create.target {
393        CreateTarget::Entity(fields) => {
394            let record = working
395                .entities
396                .get(&id)
397                .ok_or(InvertError::MissingCurrent { index, id })?;
398            let row = &record.entity;
399            check(index, id, "id", row.header.id == id)?;
400            check(
401                index,
402                id,
403                "namespace",
404                row.header.namespace == create.namespace,
405            )?;
406            check(index, id, "deleted_at", row.deleted_at.is_none())?;
407            check(index, id, "kind", row.kind == fields.entity_kind)?;
408            check(
409                index,
410                id,
411                "entity_type",
412                row.entity_type == fields.entity_type,
413            )?;
414            check(index, id, "name", row.name == fields.name)?;
415            check(
416                index,
417                id,
418                "description",
419                row.description == fields.description,
420            )?;
421            check(index, id, "properties", row.properties == fields.properties)?;
422            check(index, id, "tags", row.tags == fields.tags)?;
423            let keys: Vec<String> = fields.key.iter().cloned().collect();
424            check(index, id, "keys", same_set(&record.keys, &keys))?;
425            check(
426                index,
427                id,
428                "aliases",
429                same_set(&record.aliases, &created_aliases(fields)),
430            )?;
431            let captured = record.clone();
432            working.entities.remove(&id);
433            DeletePreimage::Entity(Box::new(captured))
434        }
435        CreateTarget::Note(fields) => {
436            let row = working
437                .notes
438                .get(&id)
439                .ok_or(InvertError::MissingCurrent { index, id })?;
440            check(index, id, "id", row.header.id == id)?;
441            check(
442                index,
443                id,
444                "namespace",
445                row.header.namespace == create.namespace,
446            )?;
447            check(index, id, "deleted_at", row.deleted_at.is_none())?;
448            check(index, id, "kind", row.kind == fields.note_kind)?;
449            check(index, id, "status", row.status == NoteStatus::default())?;
450            check(index, id, "expires_at", row.expires_at.is_none())?;
451            check(index, id, "content", row.content == fields.content)?;
452            check(index, id, "properties", row.properties == fields.properties)?;
453            check(index, id, "tags", row.tags == fields.tags)?;
454            check(index, id, "salience", row.salience == fields.salience)?;
455            check(
456                index,
457                id,
458                "decay_factor",
459                row.decay_factor == fields.decay_factor,
460            )?;
461            let captured = row.clone();
462            working.notes.remove(&id);
463            DeletePreimage::Note(Box::new(captured))
464        }
465    };
466    Ok(Op::Delete(DeleteOp {
467        target_id: id,
468        hard: false,
469        preimage,
470    }))
471}
472
473/// The aliases a staged create leaves on its entity: the requested ones other
474/// than its name, each once, with the `caller` origin.
475fn created_aliases(fields: &crate::EntityCreateFields) -> Vec<EntityAlias> {
476    fields
477        .aliases
478        .iter()
479        .filter(|alias| **alias != fields.name)
480        .collect::<BTreeSet<_>>()
481        .into_iter()
482        .map(|alias| EntityAlias {
483            alias: alias.clone(),
484            origin: EntityAliasOrigin::Caller,
485        })
486        .collect()
487}
488
489fn invert_link(index: usize, link: &LinkOp, working: &mut CurrentState) -> Result<Op, InvertError> {
490    let id = link.id;
491    let row = working
492        .edges
493        .get(&id)
494        .ok_or(InvertError::MissingCurrent { index, id })?;
495    check(index, id, "id", row.id == id)?;
496    check(
497        index,
498        id,
499        "namespace",
500        row.namespace == link.namespace.as_str(),
501    )?;
502    check(index, id, "deleted_at", row.deleted_at.is_none())?;
503    check(index, id, "source", row.source == link.source)?;
504    check(index, id, "target", row.target == link.target)?;
505    check(index, id, "relation", row.relation == link.relation)?;
506    check(index, id, "weight", row.weight == link.weight)?;
507    check(index, id, "properties", row.properties == link.properties)?;
508    let captured = row.clone();
509    working.edges.remove(&id);
510    Ok(Op::Delete(DeleteOp {
511        target_id: id,
512        hard: false,
513        preimage: DeletePreimage::Edge(Box::new(captured)),
514    }))
515}
516
517fn invert_update(
518    index: usize,
519    update: &UpdateOp,
520    working: &mut CurrentState,
521) -> Result<Op, InvertError> {
522    let id = update.target_id();
523    match (update.patch(), update.preimage()) {
524        (UpdatePatch::Entity(patch), UpdatePreimage::Entity(prior)) => {
525            let record = working
526                .entities
527                .get_mut(&id)
528                .ok_or(InvertError::MissingCurrent { index, id })?;
529            if let Some(value) = &patch.aliases {
530                check(index, id, "aliases", same_set(&record.aliases, value))?;
531            }
532            if let Some(value) = &prior.aliases {
533                record.aliases.clone_from(value);
534            }
535            let row = &mut record.entity;
536            check(index, id, "id", row.header.id == id)?;
537            if let Some(value) = &patch.name {
538                check(index, id, "name", &row.name == value)?;
539            }
540            if let Some(value) = &patch.description {
541                check(
542                    index,
543                    id,
544                    "description",
545                    row.description.as_ref() == value.as_ref(),
546                )?;
547            }
548            if let Some(value) = &patch.entity_type {
549                check(
550                    index,
551                    id,
552                    "entity_type",
553                    row.entity_type.as_ref() == value.as_ref(),
554                )?;
555            }
556            if let Some(value) = &patch.properties {
557                check(index, id, "properties", &row.properties == value)?;
558            }
559            if let Some(value) = &patch.tags {
560                check(index, id, "tags", &row.tags == value)?;
561            }
562            let inverse = swapped_update(index, update)?;
563            if let Some(value) = &prior.name {
564                row.name = value.clone();
565            }
566            if let Some(value) = &prior.description {
567                row.description = value.clone();
568            }
569            if let Some(value) = &prior.entity_type {
570                row.entity_type = value.clone();
571            }
572            if let Some(value) = &prior.properties {
573                row.properties = value.clone();
574            }
575            if let Some(value) = &prior.tags {
576                row.tags = value.clone();
577            }
578            Ok(Op::Update(inverse))
579        }
580        (UpdatePatch::Note(patch), UpdatePreimage::Note(prior)) => {
581            let row = working
582                .notes
583                .get_mut(&id)
584                .ok_or(InvertError::MissingCurrent { index, id })?;
585            check(index, id, "id", row.header.id == id)?;
586            if let Some(value) = &patch.content {
587                check(index, id, "content", &row.content == value)?;
588            }
589            if let Some(value) = patch.salience {
590                check(index, id, "salience", row.salience == value)?;
591            }
592            if let Some(value) = patch.decay_factor {
593                check(index, id, "decay_factor", row.decay_factor == value)?;
594            }
595            if let Some(value) = &patch.properties {
596                check(index, id, "properties", &row.properties == value)?;
597            }
598            if let Some(value) = &patch.tags {
599                check(index, id, "tags", &row.tags == value)?;
600            }
601            let inverse = swapped_update(index, update)?;
602            if let Some(value) = &prior.content {
603                row.content = value.clone();
604            }
605            if let Some(value) = prior.salience {
606                row.salience = value;
607            }
608            if let Some(value) = prior.decay_factor {
609                row.decay_factor = value;
610            }
611            if let Some(value) = &prior.properties {
612                row.properties = value.clone();
613            }
614            if let Some(value) = &prior.tags {
615                row.tags = value.clone();
616            }
617            Ok(Op::Update(inverse))
618        }
619        (UpdatePatch::Edge(patch), UpdatePreimage::Edge(prior)) => {
620            let row = working
621                .edges
622                .get_mut(&id)
623                .ok_or(InvertError::MissingCurrent { index, id })?;
624            check(index, id, "id", row.id == id)?;
625            if let Some(value) = patch.relation {
626                check(index, id, "relation", row.relation == value)?;
627            }
628            if let Some(value) = patch.weight {
629                check(index, id, "weight", row.weight == value)?;
630            }
631            let inverse = swapped_update(index, update)?;
632            if let Some(value) = prior.relation {
633                row.relation = value;
634            }
635            if let Some(value) = prior.weight {
636                row.weight = value;
637            }
638            Ok(Op::Update(inverse))
639        }
640        // The checked constructor and decoder prevent this pairing. Keep the
641        // refusal typed rather than panic if that invariant ever changes.
642        _ => swapped_update(index, update).map(Op::Update),
643    }
644}
645
646fn swapped_update(index: usize, update: &UpdateOp) -> Result<UpdateOp, InvertError> {
647    let patch = match update.preimage() {
648        UpdatePreimage::Entity(prior) => UpdatePatch::Entity(EntityPatch {
649            name: prior.name.clone(),
650            description: prior.description.clone(),
651            properties: prior.properties.clone(),
652            tags: prior.tags.clone(),
653            entity_type: prior.entity_type.clone(),
654            aliases: prior.aliases.clone(),
655        }),
656        UpdatePreimage::Note(prior) => UpdatePatch::Note(NotePatch {
657            content: prior.content.clone(),
658            salience: prior.salience,
659            decay_factor: prior.decay_factor,
660            properties: prior.properties.clone(),
661            tags: prior.tags.clone(),
662        }),
663        UpdatePreimage::Edge(prior) => UpdatePatch::Edge(EdgePatch {
664            relation: prior.relation,
665            weight: prior.weight,
666        }),
667    };
668    let preimage = match update.patch() {
669        UpdatePatch::Entity(patch) => UpdatePreimage::Entity(EntityPreimage {
670            name: patch.name.clone(),
671            description: patch.description.clone(),
672            properties: patch.properties.clone(),
673            tags: patch.tags.clone(),
674            entity_type: patch.entity_type.clone(),
675            aliases: patch.aliases.clone(),
676        }),
677        UpdatePatch::Note(patch) => UpdatePreimage::Note(NotePreimage {
678            content: patch.content.clone(),
679            salience: patch.salience,
680            decay_factor: patch.decay_factor,
681            properties: patch.properties.clone(),
682            tags: patch.tags.clone(),
683        }),
684        UpdatePatch::Edge(patch) => UpdatePreimage::Edge(EdgePreimage {
685            relation: patch.relation,
686            weight: patch.weight,
687        }),
688    };
689    UpdateOp::new(update.target_id(), patch, preimage)
690        .map_err(|reason| InvertError::InverseUpdate { index, reason })
691}