Skip to main content

khive_runtime/
canonical_apply.rs

1//! Ordered canonical changesets use ordinary atomic plans after writer-local checks.
2
3use std::collections::HashMap;
4use std::sync::Arc;
5
6use khive_changeset::{
7    CanonicalRecordRef, ChangeSet, CreateTarget, DeleteOp, Op, UpdateOp, UpdatePatch,
8};
9use khive_storage::{Edge, Entity, Note, SqlStatement, SqlValue, SqlWriter};
10use khive_types::EdgeEndpointRule;
11use serde_json::{json, Value};
12use uuid::Uuid;
13
14use crate::atomic_runner::{AtomicOpFailure, AtomicOpPlan};
15use crate::pack::CanonicalNoteHookLookup;
16use crate::{
17    EdgeEndpointKind, KhiveRuntime, NamespaceToken, Resolved, RuntimeError, RuntimeResult,
18    VerbRegistry,
19};
20
21/// Change-set identifiers are `Id128`; runtime records key on `Uuid`. Both carry the same 16 bytes.
22fn uuid(id: khive_types::Id128) -> Uuid {
23    Uuid::from_bytes(*id.as_bytes())
24}
25
26fn id128(id: Uuid) -> khive_types::Id128 {
27    khive_types::Id128::from_bytes(*id.as_bytes())
28}
29
30mod entities;
31mod links;
32mod notes;
33mod projection;
34mod rows;
35
36/// An opaque, admitted operation. Only this module can construct its captured state.
37#[derive(Clone)]
38pub struct CanonicalMutationPlan {
39    token: NamespaceToken,
40    request_scope: Arc<NamespaceToken>,
41    target_id: Uuid,
42    now: i64,
43    mutation: Mutation,
44}
45
46impl std::fmt::Debug for CanonicalMutationPlan {
47    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
48        // Preserve the admitted operation's existing fields without formatting caller scope.
49        f.debug_struct("CanonicalMutationPlan")
50            .field("token", &self.token)
51            .field("target_id", &self.target_id)
52            .field("now", &self.now)
53            .field("mutation", &self.mutation)
54            .finish()
55    }
56}
57
58#[derive(Clone, Debug)]
59enum Mutation {
60    Create(Box<AtomicOpPlan>),
61    Link {
62        edge: Edge,
63        rules: Vec<EdgeEndpointRule>,
64    },
65    Entity {
66        op: UpdateOp,
67        prepared: Box<entities::PreparedEntityUpdate>,
68    },
69    Note {
70        op: UpdateOp,
71        prepared: Box<notes::PreparedCanonicalNote>,
72        lookup: CanonicalNoteHookLookup,
73    },
74    Edge {
75        op: UpdateOp,
76        rules: Vec<EdgeEndpointRule>,
77    },
78    Delete {
79        op: DeleteOp,
80        plan: Box<AtomicOpPlan>,
81    },
82    Unresolved(Op),
83}
84
85#[derive(Clone, Debug)]
86enum Record {
87    Entity(Entity),
88    Note(Note),
89    Edge(Edge),
90    Event,
91}
92impl Record {
93    fn live(&self) -> bool {
94        match self {
95            Self::Entity(x) => x.deleted_at.is_none() && x.merged_into.is_none(),
96            Self::Note(x) => x.deleted_at.is_none(),
97            Self::Edge(x) => x.deleted_at.is_none(),
98            Self::Event => true,
99        }
100    }
101    fn resolved(&self) -> Option<Resolved> {
102        match self {
103            Self::Entity(x) => Some(Resolved::Entity(x.clone())),
104            Self::Note(x) => Some(Resolved::Note(x.clone())),
105            _ => None,
106        }
107    }
108    fn kind(&self) -> EdgeEndpointKind {
109        match self {
110            Self::Entity(_) => EdgeEndpointKind::Entity,
111            Self::Note(_) => EdgeEndpointKind::Note,
112            Self::Edge(_) => EdgeEndpointKind::Edge,
113            Self::Event => EdgeEndpointKind::Event,
114        }
115    }
116    fn check_update(&self, op: &UpdateOp) -> Result<(), AtomicOpFailure> {
117        let result = match self {
118            Self::Entity(x) => {
119                let mut live = projection::entity(x).map_err(storage)?;
120                if let khive_changeset::UpdatePreimage::Entity(captured) = op.preimage() {
121                    omit_unclaimed_reserved(captured.properties.as_ref(), &mut live.properties);
122                }
123                khive_changeset::check_update(op, CanonicalRecordRef::Entity(&live))
124            }
125            Self::Note(x) => {
126                let mut live = projection::note(x).map_err(storage)?;
127                if let khive_changeset::UpdatePreimage::Note(captured) = op.preimage() {
128                    omit_unclaimed_reserved(captured.properties.as_ref(), &mut live.properties);
129                }
130                khive_changeset::check_update(op, CanonicalRecordRef::Note(&live))
131            }
132            Self::Edge(x) => khive_changeset::check_update(
133                op,
134                CanonicalRecordRef::Edge(&projection::edge(x).map_err(storage)?),
135            ),
136            Self::Event => return Err(mismatch(uuid(op.target_id()), "substrate")),
137        };
138        result.map_err(|e| mismatch(uuid(op.target_id()), &e.field_path))
139    }
140    fn check_delete(&self, op: &DeleteOp) -> Result<(), AtomicOpFailure> {
141        let result = match self {
142            Self::Entity(x) => khive_changeset::check_delete(
143                op,
144                CanonicalRecordRef::Entity(&projection::entity(x).map_err(storage)?),
145            ),
146            Self::Note(x) => khive_changeset::check_delete(
147                op,
148                CanonicalRecordRef::Note(&projection::note(x).map_err(storage)?),
149            ),
150            Self::Edge(x) => khive_changeset::check_delete(
151                op,
152                CanonicalRecordRef::Edge(&projection::edge(x).map_err(storage)?),
153            ),
154            Self::Event => return Err(mismatch(uuid(op.target_id), "substrate")),
155        };
156        result.map_err(|e| mismatch(uuid(op.target_id), &e.field_path))
157    }
158}
159
160/// Prepare a bounded canonical changeset without admitting any writer work.
161///
162/// Schema, count, and unsupported operation checks run before asynchronous preparation.
163/// Every constituent is authorized with the applying caller. The returned opaque
164/// plans must run together through [`crate::run_atomic_unit`].
165pub async fn prepare_canonical_changeset(
166    runtime: &KhiveRuntime,
167    registry: &VerbRegistry,
168    token: &NamespaceToken,
169    changeset: &ChangeSet,
170) -> RuntimeResult<Vec<AtomicOpPlan>> {
171    validate(changeset)?;
172    let now = chrono::Utc::now().timestamp_micros();
173    let mut shadow: HashMap<Uuid, Option<Record>> = HashMap::new();
174    let mut plans = Vec::with_capacity(changeset.ops.len());
175    let mut hook_links: HashMap<String, (usize, Vec<crate::LinkSpec>)> = HashMap::new();
176    // Operation tokens narrow visibility; retain the caller scope only for diagnostic disclosure.
177    let request_scope = Arc::new(token.clone());
178    for (op_index, op) in changeset.ops.iter().enumerate() {
179        let prepared: RuntimeResult<AtomicOpPlan> = async {
180            let (verb, id, args) = gate_args(op)?;
181            let op_token = registry
182                .authorize_canonical_operation(token, verb, args.clone(), id)
183                .await?;
184            let mutation = match op {
185                Op::Create(create) => {
186                    if shadow.contains_key(&id) {
187                        return Err(RuntimeError::InvalidInput(
188                            "canonical staged id is reused".into(),
189                        ));
190                    }
191                    // Repeat the immutable owner draft check at this public
192                    // runtime boundary, without dispatching create lifecycle hooks.
193                    validate_create_owner(registry, create)?;
194                    let (record, plan) = match &create.target {
195                        CreateTarget::Entity(_) => {
196                            let (row, plan) = crate::atomic_prepare::prepare_add_entity_record(
197                                runtime,
198                                &op_token,
199                                &args,
200                                Some(id),
201                            )
202                            .await?;
203                            crate::atomic_prepare::canonical_refuse_registry_tags(
204                                &row.tags, "create",
205                            )?;
206                            (Record::Entity(row), plan)
207                        }
208                        CreateTarget::Note(_) => {
209                            let (row, plan) = crate::atomic_prepare::prepare_add_note_record(
210                                runtime,
211                                &op_token,
212                                &args,
213                                Some(id),
214                            )
215                            .await?;
216                            projection::note(&row)?;
217                            (Record::Note(row), plan)
218                        }
219                    };
220                    shadow.insert(id, Some(record));
221                    Mutation::Create(Box::new(plan))
222                }
223                Op::Link(link) => {
224                    if shadow.contains_key(&id) {
225                        return Err(RuntimeError::InvalidInput(
226                            "canonical staged id is reused".into(),
227                        ));
228                    }
229                    let source = read_prepare(runtime, &op_token, uuid(link.source), &mut shadow)
230                        .await?
231                        .ok_or_else(|| RuntimeError::NotFound("canonical link source".into()))?;
232                    let target = read_prepare(runtime, &op_token, uuid(link.target), &mut shadow)
233                        .await?
234                        .ok_or_else(|| RuntimeError::NotFound("canonical link target".into()))?;
235                    let rules = runtime.pack_edge_rules();
236                    links::endpoints(&source, &target, link.relation, &rules)?;
237                    if let (Record::Note(source_note), Record::Note(target_note)) =
238                        (&source, &target)
239                    {
240                        KhiveRuntime::ensure_memory_note_edge_namespace(
241                            request_scope.as_ref(),
242                            "apply_changeset",
243                            op_token.namespace().as_str(),
244                            (uuid(link.source), uuid(link.target)),
245                            link.relation,
246                            source_note,
247                            target_note,
248                        )?;
249                    }
250                    let edge = links::draft(link, &source, &target, now)?;
251                    if let Record::Note(note) = source {
252                        hook_links
253                            .entry(note.kind)
254                            .or_insert_with(|| (op_index, Vec::new()))
255                            .1
256                            .push(crate::LinkSpec {
257                                namespace: Some(link.namespace.as_str().into()),
258                                source_id: uuid(link.source),
259                                target_id: uuid(link.target),
260                                relation: link.relation,
261                                weight: link.weight,
262                                metadata: edge.metadata.clone(),
263                                resurrect: false,
264                            });
265                    }
266                    shadow.insert(id, Some(Record::Edge(edge.clone())));
267                    Mutation::Link { edge, rules }
268                }
269                Op::Update(update) => {
270                    reject_note_alias(update)?;
271                    let current = read_prepare(runtime, &op_token, id, &mut shadow).await?;
272                    match (update.patch(), current) {
273                        (UpdatePatch::Entity(_), Some(Record::Entity(row))) => {
274                            let prepared =
275                                entities::prepare(runtime, &op_token, row, update).await?;
276                            shadow.insert(id, Some(Record::Entity(prepared.projected(now)?)));
277                            Mutation::Entity {
278                                op: update.clone(),
279                                prepared: Box::new(prepared),
280                            }
281                        }
282                        (UpdatePatch::Note(_), Some(Record::Note(row))) => {
283                            reject_note_alias(update)?;
284                            let prepared =
285                                notes::prepare(runtime, registry, &op_token, row, update).await?;
286                            shadow.insert(id, Some(Record::Note(prepared.projected(now)?)));
287                            Mutation::Note {
288                                op: update.clone(),
289                                prepared: Box::new(prepared),
290                                lookup: registry.canonical_note_hook_lookup(),
291                            }
292                        }
293                        (UpdatePatch::Edge(patch), Some(Record::Edge(mut row))) => {
294                            if let Some(relation) = patch.relation {
295                                if row.source_id == row.target_id {
296                                    return Err(RuntimeError::InvalidInput(
297                                        "self-loop edges are not allowed".into(),
298                                    ));
299                                }
300                                let source =
301                                    read_prepare(runtime, &op_token, row.source_id, &mut shadow)
302                                        .await?
303                                        .ok_or_else(|| {
304                                            RuntimeError::NotFound("edge source".into())
305                                        })?;
306                                let target =
307                                    read_prepare(runtime, &op_token, row.target_id, &mut shadow)
308                                        .await?
309                                        .ok_or_else(|| {
310                                            RuntimeError::NotFound("edge target".into())
311                                        })?;
312                                links::endpoints(
313                                    &source,
314                                    &target,
315                                    relation,
316                                    &runtime.pack_edge_rules(),
317                                )?;
318                                row.relation = relation;
319                            }
320                            if let Some(weight) = patch.weight {
321                                crate::operations::validate_edge_weight(weight)?;
322                                row.weight = weight;
323                            }
324                            let (source_id, target_id) =
325                                crate::operations::canonical_edge_endpoints(
326                                    row.relation,
327                                    row.source_id,
328                                    row.target_id,
329                                );
330                            row.source_id = source_id;
331                            row.target_id = target_id;
332                            let next = row
333                                .updated_at
334                                .timestamp_micros()
335                                .checked_add(1)
336                                .ok_or_else(|| {
337                                    RuntimeError::InvalidInput("edge revision exhausted".into())
338                                })?;
339                            row.updated_at = chrono::DateTime::from_timestamp_micros(now.max(next))
340                                .ok_or_else(|| {
341                                    RuntimeError::InvalidInput("invalid edge revision".into())
342                                })?;
343                            shadow.insert(id, Some(Record::Edge(row)));
344                            Mutation::Edge {
345                                op: update.clone(),
346                                rules: runtime.pack_edge_rules(),
347                            }
348                        }
349                        _ => Mutation::Unresolved(op.clone()),
350                    }
351                }
352                Op::Delete(delete) => {
353                    reject_delete_alias(delete)?;
354                    let current = read_prepare(runtime, &op_token, id, &mut shadow).await?;
355                    let plan = match current {
356                        Some(Record::Entity(row)) => Some(
357                            crate::atomic_prepare::prepare_delete_from_snapshot(
358                                runtime,
359                                &op_token,
360                                &args,
361                                None,
362                                Some(Resolved::Entity(row)),
363                            )
364                            .await?,
365                        ),
366                        Some(Record::Note(row)) => Some(
367                            crate::atomic_prepare::prepare_delete_from_snapshot(
368                                runtime,
369                                &op_token,
370                                &args,
371                                None,
372                                Some(Resolved::Note(row)),
373                            )
374                            .await?,
375                        ),
376                        Some(Record::Edge(row)) => Some(
377                            crate::atomic_prepare::prepare_delete_edge(
378                                &op_token,
379                                id,
380                                row,
381                                delete.hard,
382                                &format!("{}:{}", op_token.actor().kind, op_token.actor().id),
383                            )
384                            .await?,
385                        ),
386                        _ => None,
387                    };
388                    shadow.insert(id, None);
389                    match plan {
390                        Some(plan) => Mutation::Delete {
391                            op: delete.clone(),
392                            plan: Box::new(plan),
393                        },
394                        None => Mutation::Unresolved(op.clone()),
395                    }
396                }
397                Op::Merge(_) | Op::Restore(_) => unreachable!("validated before prepare"),
398            };
399            Ok(AtomicOpPlan::Canonical(Box::new(CanonicalMutationPlan {
400                token: op_token,
401                request_scope: Arc::clone(&request_scope),
402                target_id: id,
403                now,
404                mutation,
405            })))
406        }
407        .await;
408        plans.push(prepared.map_err(|source| RuntimeError::CanonicalAdmission {
409            op_index,
410            source: Box::new(source),
411        })?);
412    }
413    // Preserve the owner hook's batch view so cycles spanning several links
414    // are checked together, including links from earlier staged notes.
415    for (kind, (op_index, specs)) in hook_links {
416        if let Some(hook) = registry.find_kind_hook(&kind) {
417            hook.validate_links(runtime, token, &specs)
418                .await
419                .map_err(|source| RuntimeError::CanonicalAdmission {
420                    op_index,
421                    source: Box::new(source),
422                })?;
423        }
424    }
425    Ok(plans)
426}
427
428fn validate(changeset: &ChangeSet) -> RuntimeResult<()> {
429    if changeset.envelope.schema_version != khive_changeset::CURRENT_SCHEMA_VERSION {
430        return Err(RuntimeError::InvalidInput(
431            "unsupported canonical schema_version".into(),
432        ));
433    }
434    let max = khive_types::pack::ATOMIC_MAX_OPS_DEFAULT;
435    if changeset.ops.len() > max {
436        return Err(RuntimeError::InvalidInput(format!(
437            "canonical changeset exceeds {max} operations"
438        )));
439    }
440    for (op_index, op) in changeset.ops.iter().enumerate() {
441        match op {
442            Op::Restore(_) => {
443                return Err(RuntimeError::CanonicalUnsupportedOperation {
444                    op_index,
445                    operation: "restore",
446                });
447            }
448            Op::Merge(_) => {
449                return Err(RuntimeError::CanonicalAdmission {
450                    op_index,
451                    source: Box::new(RuntimeError::InvalidInput(
452                        "KnownUnimplemented: canonical merge".into(),
453                    )),
454                });
455            }
456            _ => {}
457        }
458    }
459    Ok(())
460}
461
462fn validate_create_owner(
463    registry: &VerbRegistry,
464    create: &khive_changeset::CreateOp,
465) -> RuntimeResult<()> {
466    match &create.target {
467        CreateTarget::Entity(fields) => {
468            if let Some(hook) = registry.find_kind_hook(fields.entity_kind.name()) {
469                hook.validate_proposal_entity(&khive_types::EntityDraft {
470                    kind: fields.entity_kind.name().into(),
471                    name: fields.name.clone(),
472                    description: fields.description.clone(),
473                    properties: Some(serde_json::to_value(&fields.properties).map_err(|_| {
474                        RuntimeError::InvalidInput("invalid canonical properties".into())
475                    })?),
476                    tags: fields.tags.clone(),
477                })?;
478            }
479        }
480        CreateTarget::Note(fields) => {
481            if let Some(hook) = registry.find_kind_hook(&fields.note_kind) {
482                hook.validate_proposal_note(&khive_types::NoteDraft {
483                    kind: fields.note_kind.clone(),
484                    content: fields.content.clone(),
485                    name: None,
486                    properties: Some(serde_json::to_value(&fields.properties).map_err(|_| {
487                        RuntimeError::InvalidInput("invalid canonical properties".into())
488                    })?),
489                })?;
490            }
491        }
492    }
493    Ok(())
494}
495
496fn gate_args(op: &Op) -> RuntimeResult<(&'static str, Uuid, Value)> {
497    Ok(match op {
498        Op::Create(x) => {
499            let mut args = match &x.target {
500                CreateTarget::Entity(e) => {
501                    json!({"kind":e.entity_kind.name(),"name":e.name,"description":e.description,
502                "entity_type":e.entity_type,"properties":e.properties,"tags":e.tags})
503                }
504                CreateTarget::Note(n) => {
505                    if n.properties.contains_key("tags") {
506                        return Err(RuntimeError::InvalidInput(
507                            "canonical note properties contain tags storage alias".into(),
508                        ));
509                    }
510                    let mut properties = serde_json::to_value(&n.properties)
511                        .map_err(|_| RuntimeError::InvalidInput("invalid properties".into()))?;
512                    if !n.tags.is_empty() {
513                        properties["tags"] = json!(n.tags);
514                    }
515                    json!({"kind":n.note_kind,"content":n.content,"properties":properties,"salience":n.salience,"decay_factor":n.decay_factor})
516                }
517            };
518            args["namespace"] = json!(x.namespace.as_str());
519            ("create", uuid(x.id), args)
520        }
521        Op::Link(x) => (
522            "link",
523            uuid(x.id),
524            json!({"namespace":x.namespace.as_str(),"source_id":x.source,"target_id":x.target,
525            "relation":x.relation,"weight":x.weight,"metadata":x.properties}),
526        ),
527        Op::Update(x) => {
528            let mut args = serde_json::to_value(x.patch())
529                .map_err(|_| RuntimeError::InvalidInput("invalid canonical patch".into()))?;
530            args.as_object_mut()
531                .expect("typed patch is an object")
532                .remove("target");
533            args["id"] = json!(x.target_id());
534            ("update", uuid(x.target_id()), args)
535        }
536        Op::Delete(x) => (
537            "delete",
538            uuid(x.target_id),
539            json!({"id":x.target_id,"hard":x.hard}),
540        ),
541        Op::Restore(_) => unreachable!("validated before gate arguments"),
542        Op::Merge(_) => {
543            return Err(RuntimeError::InvalidInput(
544                "KnownUnimplemented: canonical merge".into(),
545            ))
546        }
547    })
548}
549
550async fn read_prepare(
551    runtime: &KhiveRuntime,
552    token: &NamespaceToken,
553    id: Uuid,
554    shadow: &mut HashMap<Uuid, Option<Record>>,
555) -> RuntimeResult<Option<Record>> {
556    if let Some(row) = shadow.get(&id) {
557        return Ok(row.clone());
558    }
559    let row = match runtime.resolve_by_id_including_deleted(token, id).await? {
560        Some(Resolved::Entity(x)) => Some(Record::Entity(x)),
561        Some(Resolved::Note(x)) => Some(Record::Note(x)),
562        Some(Resolved::Event(_)) => Some(Record::Event),
563        Some(Resolved::PackRecord { .. }) => {
564            return Err(RuntimeError::InvalidInput(
565                "pack-private record is not a canonical target".into(),
566            ))
567        }
568        None => runtime
569            .get_edge_including_deleted(token, id)
570            .await?
571            .map(Record::Edge),
572    };
573    shadow.insert(id, row.clone());
574    Ok(row)
575}
576
577pub(crate) async fn materialize(
578    writer: &mut dyn SqlWriter,
579    plan: &CanonicalMutationPlan,
580) -> Result<AtomicOpPlan, AtomicOpFailure> {
581    let id = plan.target_id;
582    match &plan.mutation {
583        Mutation::Create(ordinary) => {
584            identity_absent(writer, id).await?;
585            Ok((**ordinary).clone())
586        }
587        Mutation::Link { edge, rules } => {
588            identity_absent(writer, id).await?;
589            links::materialize(
590                writer,
591                &plan.token,
592                plan.request_scope.as_ref(),
593                edge,
594                rules,
595            )
596            .await
597        }
598        mutation => {
599            let live = read_writer(writer, id)
600                .await?
601                .ok_or_else(|| mismatch(id, "id"))?;
602            match mutation {
603                Mutation::Entity { op, prepared } => {
604                    live.check_update(op)?;
605                    if !live.live() {
606                        return Err(failure("canonical update target is not live"));
607                    }
608                    let Record::Entity(row) = live else {
609                        return Err(mismatch(id, "substrate"));
610                    };
611                    entities::materialize(&plan.token, row, prepared, plan.now)
612                }
613                Mutation::Note {
614                    op,
615                    prepared,
616                    lookup,
617                } => {
618                    live.check_update(op)?;
619                    if !live.live() {
620                        return Err(failure("canonical update target is not live"));
621                    }
622                    let Record::Note(row) = live else {
623                        return Err(mismatch(id, "substrate"));
624                    };
625                    let has_owner = lookup.has_hook(&row.kind);
626                    let snapshot = prepared.snapshot();
627                    if has_owner != prepared.prepared_with_owner()
628                        || has_owner
629                            && (row.updated_at != snapshot.updated_at
630                                || row.deleted_at != snapshot.deleted_at
631                                || row.version != snapshot.version)
632                    {
633                        return Err(AtomicOpFailure::OwnerSnapshotConflict {
634                            target_id: id,
635                            kind: row.kind,
636                        });
637                    }
638                    notes::materialize(&plan.token, row, prepared, plan.now)
639                }
640                Mutation::Edge { op, rules } => {
641                    live.check_update(op)?;
642                    if !live.live() {
643                        return Err(failure("canonical update target is not live"));
644                    }
645                    let Record::Edge(mut row) = live else {
646                        return Err(mismatch(id, "substrate"));
647                    };
648                    let UpdatePatch::Edge(patch) = op.patch() else {
649                        return Err(mismatch(id, "substrate"));
650                    };
651                    let old_updated = row.updated_at;
652                    let old_deleted = row.deleted_at;
653                    let mut changed = Vec::new();
654                    if let Some(relation) = patch.relation {
655                        if row.source_id == row.target_id {
656                            return Err(failure("self-loop edges are not allowed"));
657                        }
658                        let source = read_writer(writer, row.source_id)
659                            .await?
660                            .ok_or_else(|| failure("edge source is missing"))?;
661                        let target = read_writer(writer, row.target_id)
662                            .await?
663                            .ok_or_else(|| failure("edge target is missing"))?;
664                        links::endpoints(&source, &target, relation, rules)
665                            .map_err(|e| failure(e.to_string()))?;
666                        row.relation = relation;
667                        changed.push("relation");
668                    }
669                    if let Some(weight) = patch.weight {
670                        row.weight = weight;
671                        changed.push("weight");
672                    }
673                    crate::atomic_prepare::prepare_update_edge_plan(
674                        &plan.token,
675                        id,
676                        row,
677                        old_updated,
678                        old_deleted,
679                        changed,
680                        plan.now,
681                    )
682                    .map_err(|e| failure(e.to_string()))
683                }
684                Mutation::Delete { op, plan: ordinary } => {
685                    live.check_delete(op)?;
686                    Ok((**ordinary).clone())
687                }
688                Mutation::Unresolved(Op::Update(op)) => {
689                    live.check_update(op)?;
690                    Err(failure("canonical target changed after preparation"))
691                }
692                Mutation::Unresolved(Op::Delete(op)) => {
693                    live.check_delete(op)?;
694                    Err(failure("canonical target changed after preparation"))
695                }
696                _ => Err(failure("invalid canonical mutation plan")),
697            }
698        }
699    }
700}
701
702async fn identity_absent(writer: &mut dyn SqlWriter, id: Uuid) -> Result<(), AtomicOpFailure> {
703    let rows = writer
704        .query_all(
705            SqlStatement::new(
706                include_str!("../sql/canonical_identity_exists.sql"),
707                vec![SqlValue::Text(id.to_string())],
708            )
709            .labelled("canonical-id-collision"),
710        )
711        .await
712        .map_err(storage)?;
713    if rows.is_empty() {
714        Ok(())
715    } else {
716        Err(failure("canonical staged id already exists"))
717    }
718}
719async fn read_writer(
720    writer: &mut dyn SqlWriter,
721    id: Uuid,
722) -> Result<Option<Record>, AtomicOpFailure> {
723    let entity = rows::entity(writer, id).await.map_err(storage)?;
724    let note = rows::note(writer, id).await.map_err(storage)?;
725    let edge = rows::edge(writer, id).await.map_err(storage)?;
726    if usize::from(entity.is_some()) + usize::from(note.is_some()) + usize::from(edge.is_some()) > 1
727    {
728        return Err(failure("canonical record identity is ambiguous"));
729    }
730    if let Some(row) = entity {
731        return Ok(Some(Record::Entity(row)));
732    }
733    if let Some(row) = note {
734        return Ok(Some(Record::Note(row)));
735    }
736    if let Some(row) = edge {
737        return Ok(Some(Record::Edge(row)));
738    }
739    let events = writer
740        .query_all(
741            SqlStatement::new(
742                include_str!("../sql/canonical_event_exists.sql"),
743                vec![SqlValue::Text(id.to_string())],
744            )
745            .labelled("canonical-event-endpoint"),
746        )
747        .await
748        .map_err(storage)?;
749    Ok((!events.is_empty()).then_some(Record::Event))
750}
751/// ADR-115 ยง4 applied to a W1 property preimage, the same rule as the incoming map: a captured
752/// map that omits a reserved key makes no claim about it, so the live value leaves the
753/// comparison; a captured reserved value is compared like any other key.
754fn omit_unclaimed_reserved(
755    captured: Option<&std::collections::BTreeMap<String, khive_types::PropertyValue>>,
756    live: &mut std::collections::BTreeMap<String, khive_types::PropertyValue>,
757) {
758    if let Some(captured) = captured {
759        for key in crate::secret_gate::RESERVED_PROPERTY_KEYS {
760            if !captured.contains_key(key) {
761                live.remove(key);
762            }
763        }
764    }
765}
766fn mismatch(target_id: Uuid, field_path: &str) -> AtomicOpFailure {
767    AtomicOpFailure::PreimageMismatch {
768        target_id,
769        field_path: field_path.into(),
770    }
771}
772fn storage(error: khive_storage::StorageError) -> AtomicOpFailure {
773    failure(error.to_string())
774}
775fn failure(message: impl Into<String>) -> AtomicOpFailure {
776    AtomicOpFailure::SqlError {
777        statement_label: Some("canonical-materialize".into()),
778        message: message.into(),
779    }
780}
781fn reject_note_alias(op: &UpdateOp) -> RuntimeResult<()> {
782    let conflict = matches!(op.patch(),UpdatePatch::Note(p) if p.properties.as_ref().is_some_and(|m|m.contains_key("tags")))
783        || matches!(op.preimage(),khive_changeset::UpdatePreimage::Note(p) if p.properties.as_ref().is_some_and(|m|m.contains_key("tags")));
784    if conflict {
785        return Err(RuntimeError::InvalidInput(
786            "canonical note properties contain tags storage alias".into(),
787        ));
788    }
789    Ok(())
790}
791fn reject_delete_alias(op: &DeleteOp) -> RuntimeResult<()> {
792    if matches!(&op.preimage,khive_changeset::DeletePreimage::Note(n) if n.properties.contains_key("tags"))
793    {
794        return Err(RuntimeError::InvalidInput(
795            "canonical note properties contain tags storage alias".into(),
796        ));
797    }
798    Ok(())
799}
800
801#[cfg(test)]
802mod reserved_property_tests;
803#[cfg(test)]
804mod tests;