Skip to main content

khive_runtime/atomic_prepare/
edge_delete.rs

1use super::{
2    canonical_edge_endpoints, delete_record_attachments_statement, edge_hard_delete_statement,
3    edge_replace_if_unchanged_statement, edge_soft_delete_statement,
4    edge_symmetric_absorb_or_update_inplace_statement, edge_symmetric_delete_if_conflict_statement,
5    entity_hard_delete_statement, entity_soft_delete_statement, event_append_statements,
6    hard_delete_lineage_warning_statements, note_hard_delete_statement, note_soft_delete_statement,
7    obj, optional_f64, optional_properties, optional_str, parse_edge_relation,
8    purge_incident_edges_statement, push_index_purge_statements, refuse_pack_registry_tags,
9    reject_inapplicable_update_fields, require_uuid, AffectedRowGuard, AtomicOpPlan,
10    AttachmentSubstrate, DeletePlan, EdgeNaturalKey, EventKind, KhiveRuntime, NamespaceToken,
11    PlanStatement, PostCommitEffect, Resolved, RuntimeError, RuntimeResult, SubstrateKind,
12    UpdatePlan, Uuid, Value,
13};
14
15impl KhiveRuntime {
16    /// Merge an edge properties patch; omitted keys survive and null stays literal.
17    pub(crate) fn merge_edge_properties(metadata: &Option<Value>, patch: Value) -> Option<Value> {
18        crate::curation::merge_properties(
19            metadata,
20            &Some(patch),
21            crate::curation::EntityDedupMergePolicy::PreferFrom,
22        )
23        .0
24    }
25}
26
27/// Edge branch of `prepare_update`. Mirrors `KhiveRuntime::update_edge`'s
28/// patch semantics: `relation`/`weight`/`properties` are the only applicable
29/// fields, a changed `relation` is endpoint-validated first, `weight` is
30/// range-checked, and `properties` shallow-merges into `metadata`: patch keys
31/// replace existing values, omitted keys are preserved, and null is stored
32/// as a literal value.
33/// See `docs/api/atomic_prepare.md#prepare_update_edge` for the DML-shape parity
34/// detail with `update_edge`.
35///
36/// Invariant (symmetric relations `competes_with`/`composed_with`): this
37/// function must never branch on a prepare-time conflict probe — a different
38/// op in the same atomic unit could change the conflict landscape between
39/// probe and commit, making any such branch stale by construction. It always
40/// emits BOTH statements from [`edge_symmetric_delete_if_conflict_statement`]
41/// and [`edge_symmetric_absorb_or_update_inplace_statement`], each carrying
42/// its own commit-time `WHERE`/`CASE WHEN` predicate that re-evaluates the
43/// conflict condition fresh inside the transaction. This function reads no
44/// state to guess a surviving id; the plan instead carries `edge_natural_key`
45/// so a post-commit caller derives the actual surviving id from the
46/// committed row, never from a value computed before the rest of this atomic
47/// unit has even run.
48pub(super) async fn prepare_update_edge(
49    runtime: &KhiveRuntime,
50    token: &NamespaceToken,
51    id: Uuid,
52    mut edge: khive_storage::types::Edge,
53    args: &Value,
54) -> RuntimeResult<AtomicOpPlan> {
55    reject_inapplicable_update_fields(args, "edge")?;
56
57    let expected_updated_at = edge.updated_at;
58    let expected_deleted_at = edge.deleted_at;
59
60    let relation_raw = optional_str(args, "relation");
61    let weight = optional_f64(args, "weight")?;
62    let properties = optional_properties(args, "properties")?;
63
64    if let Some(ref p) = properties {
65        crate::secret_gate::check_json_at(p, "edge", "properties")?;
66    }
67    crate::secret_gate::reject_reserved_secret_gate_property(properties.as_ref())?;
68
69    let namespace = edge.namespace.clone();
70    let record_tok = token.with_namespace(
71        khive_types::Namespace::parse(&namespace)
72            .map_err(|e| RuntimeError::Internal(format!("edge namespace invalid: {e}")))?,
73    );
74
75    let mut changed_fields: Vec<&'static str> = Vec::new();
76    if let Some(raw) = relation_raw {
77        let relation = parse_edge_relation(raw)?;
78        runtime
79            .validate_edge_relation_endpoints(&record_tok, edge.source_id, edge.target_id, relation)
80            .await?;
81        edge.relation = relation;
82        changed_fields.push("relation");
83    }
84    if let Some(w) = weight {
85        if !khive_types::validate_edge_weight(w) {
86            return Err(RuntimeError::InvalidInput(format!(
87                "edge weight must be a finite value in [0.0, 1.0]; got {w}"
88            )));
89        }
90        edge.weight = w;
91        changed_fields.push("weight");
92    }
93    if let Some(p) = properties {
94        edge.metadata = KhiveRuntime::merge_edge_properties(&edge.metadata, p);
95        changed_fields.push("properties");
96    }
97
98    prepare_update_edge_plan(
99        token,
100        id,
101        edge,
102        expected_updated_at,
103        expected_deleted_at,
104        changed_fields,
105        chrono::Utc::now().timestamp_micros(),
106    )
107}
108
109pub(crate) fn prepare_update_edge_plan(
110    token: &NamespaceToken,
111    id: Uuid,
112    mut edge: khive_storage::Edge,
113    expected_updated_at: chrono::DateTime<chrono::Utc>,
114    expected_deleted_at: Option<chrono::DateTime<chrono::Utc>>,
115    changed_fields: Vec<&'static str>,
116    now_micros: i64,
117) -> RuntimeResult<AtomicOpPlan> {
118    let namespace = edge.namespace.clone();
119    let (canon_src, canon_tgt) =
120        canonical_edge_endpoints(edge.relation, edge.source_id, edge.target_id);
121    let now = chrono::DateTime::from_timestamp_micros(now_micros).ok_or_else(|| {
122        RuntimeError::InvalidInput("invalid canonical edge write timestamp".into())
123    })?;
124
125    let mut statements: Vec<PlanStatement> = Vec::new();
126    let mut edge_natural_key: Option<EdgeNaturalKey> = None;
127
128    if edge.relation.is_symmetric() {
129        // The write for a symmetric relation never branches on a
130        // prepare-time probe result: it always carries both self-guarding,
131        // commit-time-predicate statements (see their doc comment in
132        // khive-db's graph.rs for the full rationale). This avoids the
133        // staleness window a prepare-time probe would expose: an earlier op
134        // in the same atomic unit could change the conflict landscape before
135        // commit. Canonical's own probe-then-branch
136        // `update_edge_symmetric_dml` has no such exposure (single
137        // transaction, no interleaving) and is unaffected.
138        let metadata_str = edge
139            .metadata
140            .as_ref()
141            .map(|v| serde_json::to_string(v).unwrap_or_default());
142
143        // `updated_at` must strictly advance past the snapshot even when two
144        // operations land inside one clock microsecond; saturating to
145        // i64::MAX would let the CAS accept a write without advancing its
146        // revision, so that is not a valid fallback (mirrors the note path).
147        let minimum_updated_at_micros = expected_updated_at
148            .timestamp_micros()
149            .checked_add(1)
150            .ok_or_else(|| {
151                RuntimeError::Internal(format!(
152                    "edge {id} updated_at is already at i64::MAX and cannot advance"
153                ))
154            })?;
155        let symmetric_updated_at_micros = now.timestamp_micros().max(minimum_updated_at_micros);
156        let expected_deleted_at_micros = expected_deleted_at.map(|v| v.timestamp_micros());
157
158        statements.push(PlanStatement {
159            statement: edge_symmetric_delete_if_conflict_statement(
160                &namespace,
161                id,
162                canon_src,
163                canon_tgt,
164                edge.relation,
165                expected_updated_at.timestamp_micros(),
166                expected_deleted_at_micros,
167            ),
168            guard: Some(AffectedRowGuard {
169                expected_min: 0,
170                expected_max: Some(1),
171            }),
172        });
173        statements.push(PlanStatement {
174            statement: edge_symmetric_absorb_or_update_inplace_statement(
175                &namespace,
176                id,
177                canon_src,
178                canon_tgt,
179                edge.relation,
180                edge.weight,
181                symmetric_updated_at_micros,
182                metadata_str.as_deref(),
183                edge.target_backend.as_deref(),
184                expected_updated_at.timestamp_micros(),
185                expected_deleted_at_micros,
186            ),
187            guard: Some(AffectedRowGuard::exactly(1)),
188        });
189
190        // No prepare-time read needed: the two statements above are
191        // self-guarding at commit time (see their doc comment). Post-commit
192        // result rendering derives the actual surviving id from THIS
193        // natural key, never from a value computed here.
194        edge_natural_key = Some(EdgeNaturalKey {
195            namespace: namespace.clone(),
196            canon_source_id: canon_src,
197            canon_target_id: canon_tgt,
198            relation: edge.relation,
199        });
200    } else {
201        // Non-symmetric: guarded replace of the read snapshot rather than
202        // `graph.upsert_edge`'s unconditional natural-key upsert — a zero
203        // affected-row result now means a concurrent writer moved this edge
204        // between PREPARE and commit, and the atomic unit must roll back
205        // instead of silently overwriting it.
206        //
207        // `updated_at` must strictly advance past the snapshot even when two
208        // operations land inside one clock microsecond; saturating to
209        // i64::MAX would let the CAS accept a write without advancing its
210        // revision, so that is not a valid fallback (mirrors the note path).
211        let minimum_updated_at_micros = expected_updated_at
212            .timestamp_micros()
213            .checked_add(1)
214            .ok_or_else(|| {
215                RuntimeError::Internal(format!(
216                    "edge {id} updated_at is already at i64::MAX and cannot advance"
217                ))
218            })?;
219        let now_micros = now.timestamp_micros().max(minimum_updated_at_micros);
220        edge.updated_at = chrono::DateTime::from_timestamp_micros(now_micros).ok_or_else(|| {
221            RuntimeError::Internal(format!(
222                "edge {id}: computed updated_at {now_micros} is not a valid timestamp"
223            ))
224        })?;
225        statements.push(PlanStatement {
226            statement: edge_replace_if_unchanged_statement(
227                &edge,
228                expected_updated_at,
229                expected_deleted_at,
230            ),
231            guard: Some(AffectedRowGuard::exactly(1)),
232        });
233    }
234
235    // Mirrors `update_edge`'s unconditional post-mutation `EdgeUpdated`
236    // event append, keyed on the original `edge_id` the caller supplied:
237    // canonical does the same (the event target is `edge_id`, not the
238    // post-absorption surviving id).
239    statements.extend(event_append_statements(
240        token,
241        &namespace,
242        "update",
243        EventKind::EdgeUpdated,
244        SubstrateKind::Entity,
245        id,
246        serde_json::json!({"id": id, "namespace": namespace, "changed_fields": changed_fields}),
247    )?);
248
249    Ok(AtomicOpPlan::Update(Box::new(UpdatePlan {
250        graph_effects: Vec::new(),
251        note_vector_purge: None,
252        note_embedding_inheritance: None,
253        entity_guard: None,
254        note_guard: None,
255        target_id: id,
256        statements,
257        post_commit: PostCommitEffect::None,
258        edge_natural_key,
259        idempotent_noop: false,
260    })))
261}
262
263// ---------------------------------------------------------------------------
264// delete
265// ---------------------------------------------------------------------------
266
267/// Caller-supplied delete-kind expectation, resolved via the canonical
268/// `resolve_kind_spec` at the kkernel `--atomic` seam. `khive-runtime` must
269/// not depend on `khive-pack-kg` (packs depend on the runtime, not the other
270/// way around), so this is a plain substrate-level shape rather than
271/// `khive_pack_kg::handlers::KindSpec` itself: the kkernel seam does the
272/// pack-aware `resolve_kind_spec` resolution (which needs a `VerbRegistry`,
273/// unreachable from this crate) and passes down only what `prepare_delete`
274/// needs to enforce the mismatch check.
275///
276/// `delete` admits `kind="edge"` per `ATOMIC_ADMISSIBLE_VERBS`, hence the
277/// `Edge` variant. `Event`/`Proposal` remain rejected at the kkernel seam
278/// (not v1-admissible for atomic delete at all).
279pub enum AtomicDeleteKind {
280    Entity {
281        specific: Option<String>,
282        entity_type: Option<String>,
283    },
284    Note {
285        specific: Option<String>,
286    },
287    Edge,
288}
289
290/// `expected_kind`: `None` when the caller omitted `kind` (no check, parity
291/// with canonical's own optional discriminator); `Some(_)` enforces an
292/// exact-parity mismatch check against the resolved record's actual
293/// substrate/specific kind, mirroring `handle_delete`'s
294/// `entity.kind != *expected` / `note.kind != *expected` checks.
295pub async fn prepare_delete(
296    runtime: &KhiveRuntime,
297    token: &NamespaceToken,
298    args: &Value,
299    expected_kind: Option<AtomicDeleteKind>,
300) -> RuntimeResult<AtomicOpPlan> {
301    let id = require_uuid(args, "id")?;
302    let hard = obj(args)?
303        .get("hard")
304        .and_then(|v| v.as_bool())
305        .unwrap_or(false);
306
307    // `delete(id, hard=true)` is the public purge route after a prior soft
308    // delete, so it must resolve including already-tombstoned rows (a
309    // live-only resolve would never find one). Soft delete keeps the
310    // live-only resolve: a soft delete of an already-tombstoned row is a
311    // no-op, matching non-atomic behavior.
312    let resolved = if hard {
313        runtime.resolve_by_id_including_deleted(token, id).await?
314    } else {
315        runtime.resolve_by_id(token, id).await?
316    };
317
318    prepare_delete_from_snapshot(runtime, token, args, expected_kind, resolved).await
319}
320
321pub(crate) async fn prepare_delete_from_snapshot(
322    runtime: &KhiveRuntime,
323    token: &NamespaceToken,
324    args: &Value,
325    expected_kind: Option<AtomicDeleteKind>,
326    resolved: Option<Resolved>,
327) -> RuntimeResult<AtomicOpPlan> {
328    let id = require_uuid(args, "id")?;
329    let actor = format!("{}:{}", token.actor().kind, token.actor().id);
330    let hard = obj(args)?
331        .get("hard")
332        .and_then(|v| v.as_bool())
333        .unwrap_or(false);
334
335    match resolved {
336        Some(Resolved::Entity(entity)) => {
337            match &expected_kind {
338                None => {}
339                Some(AtomicDeleteKind::Entity {
340                    specific: Some(expected),
341                    ..
342                }) if &entity.kind != expected => {
343                    return Err(RuntimeError::NotFound(format!("{expected} {id}")));
344                }
345                Some(AtomicDeleteKind::Entity { .. }) => {}
346                Some(AtomicDeleteKind::Note { .. }) => {
347                    return Err(RuntimeError::NotFound(format!("note {id}")));
348                }
349                Some(AtomicDeleteKind::Edge) => {
350                    return Err(RuntimeError::NotFound(format!("edge {id}")));
351                }
352            }
353            if let Some(AtomicDeleteKind::Entity {
354                entity_type: Some(expected),
355                ..
356            }) = &expected_kind
357            {
358                if entity
359                    .entity_type
360                    .as_deref()
361                    .is_some_and(|actual| actual != expected.as_str())
362                {
363                    return Err(RuntimeError::NotFound(format!("entity {id}")));
364                }
365            }
366            refuse_pack_registry_tags(&entity.tags, "delete")?;
367            let namespace = entity.namespace.clone();
368            // Storage parity: `entity_soft_delete_statement`/
369            // `entity_hard_delete_statement` are the SAME khive-db builders
370            // khive-db's own `SqlEntityStore::delete_entity` calls — no DML
371            // text is hand-duplicated here.
372            let mut statements = if hard {
373                vec![
374                    PlanStatement {
375                        statement: delete_record_attachments_statement(
376                            id,
377                            AttachmentSubstrate::Entity,
378                        ),
379                        guard: None,
380                    },
381                    PlanStatement {
382                        statement: entity_hard_delete_statement(id),
383                        guard: Some(AffectedRowGuard::exactly(1)),
384                    },
385                ]
386            } else {
387                let deleted_at = chrono::Utc::now().timestamp_micros();
388                vec![PlanStatement {
389                    statement: entity_soft_delete_statement(id, deleted_at),
390                    guard: Some(AffectedRowGuard::exactly(1)),
391                }]
392            };
393            if hard {
394                statements.extend(
395                    hard_delete_lineage_warning_statements(
396                        &namespace,
397                        &actor,
398                        id,
399                        SubstrateKind::Entity,
400                    )
401                    .into_iter()
402                    .map(|statement| PlanStatement {
403                        statement,
404                        guard: None,
405                    }),
406                );
407                // Same builder canonical `delete_entity`'s hard-delete
408                // cascade calls (`graph.purge_incident_edges`).
409                statements.push(PlanStatement {
410                    statement: purge_incident_edges_statement(id),
411                    guard: None,
412                });
413            }
414            // FTS + vector index purge, matching operations.rs
415            // `delete_entity`: both soft and hard delete clean indexes (a
416            // hard delete of an already-tombstoned record must still purge
417            // them); only hard additionally cascades edges above.
418            push_index_purge_statements(
419                runtime,
420                &mut statements,
421                "fts_entities",
422                &namespace,
423                id,
424                "atomic-delete-entity",
425            )
426            .await?;
427            // operations.rs's `delete_entity` appends an `EntityDeleted`
428            // event after a successful row delete, on both soft and hard
429            // delete. `apply_plan` never reaches this statement unless the
430            // guarded row statement above affected a row, so no extra `if`
431            // is needed here.
432            statements.extend(event_append_statements(
433                token,
434                &namespace,
435                "delete",
436                EventKind::EntityDeleted,
437                SubstrateKind::Entity,
438                id,
439                serde_json::json!({"id": id, "namespace": namespace, "hard": hard}),
440            )?);
441            Ok(AtomicOpPlan::Delete(DeletePlan {
442                target_id: id,
443                statements,
444                post_commit: PostCommitEffect::None,
445            }))
446        }
447        Some(Resolved::Note(note)) => {
448            match &expected_kind {
449                None => {}
450                Some(AtomicDeleteKind::Note {
451                    specific: Some(expected),
452                }) if &note.kind != expected => {
453                    return Err(RuntimeError::NotFound(format!("{expected} {id}")));
454                }
455                Some(AtomicDeleteKind::Note { .. }) => {}
456                Some(AtomicDeleteKind::Entity { .. }) => {
457                    return Err(RuntimeError::NotFound(format!("entity {id}")));
458                }
459                Some(AtomicDeleteKind::Edge) => {
460                    return Err(RuntimeError::NotFound(format!("edge {id}")));
461                }
462            }
463            if let Some(error) = runtime.stream_member_error(&note).await? {
464                return Err(error);
465            }
466            let mut index_statements = Vec::new();
467            push_index_purge_statements(
468                runtime,
469                &mut index_statements,
470                "fts_notes",
471                &note.namespace,
472                id,
473                "atomic-delete-note",
474            )
475            .await?;
476            note_delete_plan(
477                token,
478                id,
479                &note.namespace,
480                &note.kind,
481                hard,
482                index_statements,
483            )
484        }
485        Some(_) => Err(RuntimeError::InvalidInput(format!(
486            "delete target {id} must be an entity, note, or edge"
487        ))),
488        // `Resolved` has no `Edge` variant (same reasoning as
489        // `prepare_update`'s fallback above) — probe the graph store
490        // directly.
491        None => match &expected_kind {
492            Some(AtomicDeleteKind::Entity { .. }) => {
493                Err(RuntimeError::NotFound(format!("entity/note {id}")))
494            }
495            Some(AtomicDeleteKind::Note { .. }) => {
496                Err(RuntimeError::NotFound(format!("entity/note {id}")))
497            }
498            Some(AtomicDeleteKind::Edge) | None => {
499                let edge = if hard {
500                    runtime.get_edge_including_deleted(token, id).await?
501                } else {
502                    runtime.get_edge(token, id).await?
503                };
504                match edge {
505                    Some(edge) => prepare_delete_edge(token, id, edge, hard, &actor).await,
506                    None => Err(RuntimeError::NotFound(format!("entity/note/edge {id}"))),
507                }
508            }
509        },
510    }
511}
512
513/// Edge branch of `prepare_delete`. Mirrors
514/// `khive-runtime::operations::KhiveRuntime::delete_edge` exactly: hard
515/// delete cascades `purge_incident_edges` (any `annotates` edge — or any
516/// other edge — pointing AT this edge as a node) BEFORE deleting the edge
517/// row itself, then a soft or hard delete statement, then an unconditional
518/// `EdgeDeleted` event (edges are never FTS/vector-indexed, so unlike the
519/// entity/note branches there is no index purge here — `delete_edge` has
520/// none either).
521pub(crate) async fn prepare_delete_edge(
522    token: &NamespaceToken,
523    id: Uuid,
524    edge: khive_storage::types::Edge,
525    hard: bool,
526    actor: &str,
527) -> RuntimeResult<AtomicOpPlan> {
528    let namespace = edge.namespace.clone();
529    let mut statements: Vec<PlanStatement> = Vec::new();
530
531    if hard {
532        statements.extend(
533            hard_delete_lineage_warning_statements(&namespace, actor, id, SubstrateKind::Entity)
534                .into_iter()
535                .map(|statement| PlanStatement {
536                    statement,
537                    guard: None,
538                }),
539        );
540        // Mirrors `delete_edge`'s `graph.purge_incident_edges(edge_id)` —
541        // unguarded: zero incident edges is a legitimate outcome, not a
542        // failure (same reasoning as the entity/note cascade-edges
543        // statements above).
544        statements.push(PlanStatement {
545            statement: purge_incident_edges_statement(id),
546            guard: None,
547        });
548        statements.push(PlanStatement {
549            statement: edge_hard_delete_statement(id),
550            guard: Some(AffectedRowGuard::exactly(1)),
551        });
552    } else {
553        let now = chrono::Utc::now().timestamp_micros();
554        statements.push(PlanStatement {
555            statement: edge_soft_delete_statement(id, now),
556            guard: Some(AffectedRowGuard::exactly(1)),
557        });
558    }
559
560    statements.extend(event_append_statements(
561        token,
562        &namespace,
563        "delete",
564        EventKind::EdgeDeleted,
565        SubstrateKind::Entity,
566        id,
567        serde_json::json!({"id": id, "namespace": namespace, "hard": hard}),
568    )?);
569
570    Ok(AtomicOpPlan::Delete(DeletePlan {
571        target_id: id,
572        statements,
573        post_commit: PostCommitEffect::None,
574    }))
575}
576
577/// Build canonical note deletion after the caller has established authority and
578/// membership. A stream caller must remove the authorized ledger rows in the
579/// same applying transaction before these guarded note statements can run.
580pub(crate) fn note_delete_plan(
581    token: &NamespaceToken,
582    id: Uuid,
583    namespace: &str,
584    kind: &str,
585    hard: bool,
586    index_statements: Vec<PlanStatement>,
587) -> RuntimeResult<AtomicOpPlan> {
588    let actor = format!("{}:{}", token.actor().kind, token.actor().id);
589    // Storage parity: `note_soft_delete_statement`/
590    // `note_hard_delete_statement` are the SAME khive-db builders
591    // khive-db's own `SqlNoteStore::delete_note` calls.
592    let mut statements = if hard {
593        vec![
594            PlanStatement {
595                statement: delete_record_attachments_statement(id, AttachmentSubstrate::Note),
596                guard: None,
597            },
598            PlanStatement {
599                statement: note_hard_delete_statement(id),
600                guard: Some(AffectedRowGuard::exactly(1)),
601            },
602        ]
603    } else {
604        let deleted_at = chrono::Utc::now().timestamp_micros();
605        vec![PlanStatement {
606            statement: note_soft_delete_statement(id, deleted_at),
607            guard: Some(AffectedRowGuard::exactly(1)),
608        }]
609    };
610    if hard {
611        statements.extend(
612            hard_delete_lineage_warning_statements(namespace, &actor, id, SubstrateKind::Note)
613                .into_iter()
614                .map(|statement| PlanStatement {
615                    statement,
616                    guard: None,
617                }),
618        );
619        statements.push(PlanStatement {
620            statement: purge_incident_edges_statement(id),
621            guard: None,
622        });
623    }
624    // FTS + vector index purge, matching operations.rs
625    // `delete_note`: both soft and hard delete clean indexes (a hard
626    // delete of an already-tombstoned record must still purge
627    // them); only hard additionally cascades edges above.
628    statements.extend(index_statements);
629    // operations.rs's `delete_note` appends a `NoteDeleted` event
630    // after a successful row delete, on both soft and hard delete:
631    // same reasoning as the entity branch above.
632    statements.extend(event_append_statements(
633        token,
634        namespace,
635        "delete",
636        EventKind::NoteDeleted,
637        SubstrateKind::Note,
638        id,
639        serde_json::json!({"id": id, "namespace": namespace, "hard": hard}),
640    )?);
641    Ok(AtomicOpPlan::Delete(DeletePlan {
642        target_id: id,
643        statements,
644        // A committed atomic note delete must fire the same
645        // pack-installed note-mutation hook `operations.rs::
646        // delete_note` fires, so a warm ANN cache sees the deletion
647        // even when the mutation went through the atomic-plan path.
648        post_commit: PostCommitEffect::NoteDeleted {
649            note_id: id,
650            kind: kind.to_owned(),
651        },
652    }))
653}