khive_runtime/atomic_plan.rs
1//! ADR-099 (cross-op atomicity for bulk apply) — prepared write-plan types.
2//!
3//! Async prepare materializes a synchronous write plan outside any
4//! transaction; commit later applies its statements as DML under a per-op
5//! SAVEPOINT. This module defines the plan *shapes* only, one family per
6//! admissible verb group (`update`, `delete`, `link`, `merge`,
7//! `gtd.transition`, `gtd.complete`, the governance verbs) — not yet wired
8//! into a live handler or the dispatch path. Every plan is deliberately
9//! inert (plain data, no async, no embedding reference).
10//!
11//! Two validation-staleness invariants every plan must satisfy:
12//! 1. **Predicate-based plans** carry an "all rows matching a condition"
13//! effect as a statement evaluated inside the transaction
14//! (`PlanPredicate`), never as a prepare-time-enumerated row list.
15//! 2. **Affected-row guards** (`PlanStatement::guard`) are attached to the
16//! exact statement they validate, checked in-transaction; a mismatch
17//! fails the op and rolls back the whole unit.
18//!
19//! See `docs/atomic-plan.md` for why guards are per-statement rather than
20//! per-plan.
21
22use uuid::Uuid;
23
24use khive_storage::SqlStatement;
25
26/// One statement in a plan, paired with the guard (if any) that validates
27/// it. **Runner contract:** a present `guard` is checked against the
28/// affected-row count of applying `statement` alone (`SqlWriter::execute`'s
29/// return value for this statement), not a batch total and not another
30/// statement's count. `guard: None` means prepare made no row-existence
31/// assumption about this particular statement (e.g. a cascade delete that
32/// may legitimately touch zero rows).
33#[derive(Debug, Clone)]
34pub struct PlanStatement {
35 /// The DML to apply inside the atomic unit.
36 pub statement: SqlStatement,
37 /// The expected-effect guard for `statement`, if prepare's validation
38 /// assumed a target row exists for it.
39 pub guard: Option<AffectedRowGuard>,
40}
41
42/// The predicate a prepare pass validated a plan's target against, replayed
43/// as a statement evaluated **inside** the transaction (ADR-099 D1, rule 1:
44/// "predicate-based plans wherever a write's scope depends on current
45/// state"). Carrying the predicate rather than a prepare-time-enumerated row
46/// list is what lets a later op in the same file (e.g. an intervening
47/// `link`) be visible to this plan's apply.
48#[derive(Debug, Clone)]
49pub struct PlanPredicate {
50 /// Human-readable description of the condition, for diagnostics (e.g.
51 /// `"source_id = :from"`).
52 pub description: String,
53 /// The in-transaction statement whose scope is evaluated against
54 /// current (committed-so-far) state, not prepare-time state.
55 pub statement: SqlStatement,
56}
57
58/// An affected-row guard (ADR-099 D1, rule 2): the row-count prepare assumed
59/// its target write would affect, re-verified in-transaction. A prepare-time
60/// validation is a plan *hypothesis*, never a commitment — if the guard does
61/// not hold at apply time, the op fails inside the atomic unit and the whole
62/// unit rolls back (ADR-099 acceptance criteria: "zero-row apply fails the
63/// unit").
64#[derive(Debug, Clone, Copy, PartialEq, Eq)]
65pub struct AffectedRowGuard {
66 /// Minimum affected-row count for the guard to hold (inclusive).
67 pub expected_min: u64,
68 /// Maximum affected-row count for the guard to hold (inclusive), or
69 /// `None` for "no upper bound" (e.g. a predicate-based rewire that may
70 /// touch any number of rows).
71 pub expected_max: Option<u64>,
72}
73
74impl AffectedRowGuard {
75 /// A guard requiring exactly `n` affected rows (the common case for a
76 /// single-target `update`/`delete`/`link` statement).
77 pub fn exactly(n: u64) -> Self {
78 Self {
79 expected_min: n,
80 expected_max: Some(n),
81 }
82 }
83
84 /// A guard requiring at least one affected row and no upper bound (the
85 /// shape for a predicate-based rewire that may touch any number of rows,
86 /// e.g. `merge`'s edge rewire).
87 pub fn at_least_one() -> Self {
88 Self {
89 expected_min: 1,
90 expected_max: None,
91 }
92 }
93
94 /// Whether an observed affected-row count satisfies this guard.
95 pub fn holds_for(&self, affected: u64) -> bool {
96 affected >= self.expected_min
97 && self.expected_max.map(|max| affected <= max).unwrap_or(true)
98 }
99}
100
101/// A deferred side effect recorded during prepare and run once, after the
102/// atomic unit commits (ADR-099 D1, "post-commit pass"). v1's admissible set
103/// computes no embeddings during prepare (D3's `update`/`merge` caveat), so
104/// the only post-commit effects are reindex kicks computed from the
105/// **committed** row content, plus the GAP-5 addition under B3: the
106/// best-effort GTD lifecycle audit row.
107#[derive(Debug, Clone, PartialEq, Eq)]
108pub enum PostCommitEffect {
109 /// No deferred side effect for this op.
110 None,
111 /// Re-embed and re-warm the given entity's vector row from its committed
112 /// content (ADR-099 D3 `update` caveat: entity name/description change).
113 ReindexEntity { entity_id: Uuid },
114 /// Re-embed and re-warm the given note's vector row from its committed
115 /// content (ADR-099 D3 `update` caveat: note name/content change).
116 ReindexNote { note_id: Uuid },
117 /// Append one `gtd_lifecycle_audit` row for a committed `gtd.transition`
118 /// or `gtd.complete` (ADR-099 B3, GAP-5): canonical `handle_transition`/
119 /// `handle_complete` call `ensure_audit_schema` +
120 /// `write_audit_record_with_status`
121 /// (`khive-pack-gtd::handlers`) as a best-effort side write — a failed
122 /// audit insert must never roll back an already-committed transition.
123 /// Carries exactly the fields the lifecycle-audit helper needs. Applied
124 /// outside `khive-runtime` (crate-direction: `khive-pack-gtd` depends on
125 /// `khive-runtime`, not the other way around) — this crate's own
126 /// `apply_post_commit_effects` treats this variant as a no-op; the
127 /// `kkernel` caller that owns both crates applies it by calling the
128 /// canonical `ensure_audit_schema`/`write_audit_record_with_status`
129 /// functions
130 /// directly.
131 GtdAudit {
132 task_id: Uuid,
133 from_status: String,
134 to_status: String,
135 note: Option<String>,
136 namespace: String,
137 },
138 /// A committed note delete (soft or hard) — fire the pack-installed
139 /// note-mutation hook with the deleted note's kind (#750:
140 /// `DeletePlan` previously carried no `post_commit`
141 /// slot at all, so an atomic note delete never reached
142 /// `KhiveRuntime::fire_note_mutation_hook`, unlike `operations.rs`'s
143 /// `delete_note`, which fires it directly after a successful row
144 /// delete). Entity deletes have no equivalent — the hook system is
145 /// note-only (`khive-pack-memory`'s warm ANN cache is the only
146 /// installed consumer today).
147 NoteDeleted { note_id: Uuid, kind: String },
148}
149
150/// The natural key a committed symmetric edge update's surviving row must
151/// be looked up by (ADR-099 B3, second
152/// half). `khive-db`'s `edge_symmetric_absorb_or_update_inplace_statement`
153/// pair never trusts a prepare-time-computed target id (see that builder's
154/// doc comment); a caller rendering this op's result derives the actual
155/// surviving id by querying `graph_edges`'s own
156/// `UNIQUE(namespace, source_id, target_id, relation)` constraint via
157/// `KhiveRuntime::get_edge_by_natural_key_including_deleted`, which — unlike
158/// `list_edges` — includes soft-deleted rows: the ADR-039 DO NOTHING absorption
159/// arm can commit leaving the surviving canonical row tombstoned
160/// (khive#1213/#1214), and `list_edges` would report "not found" for exactly
161/// that row. Looked up strictly after commit.
162#[derive(Debug, Clone)]
163pub struct EdgeNaturalKey {
164 pub(crate) namespace: String,
165 pub(crate) canon_source_id: Uuid,
166 pub(crate) canon_target_id: Uuid,
167 pub(crate) relation: khive_storage::EdgeRelation,
168}
169
170impl EdgeNaturalKey {
171 /// The namespace containing the surviving edge.
172 pub fn namespace(&self) -> &str {
173 &self.namespace
174 }
175
176 /// The canonical source endpoint of the surviving edge.
177 pub fn canon_source_id(&self) -> Uuid {
178 self.canon_source_id
179 }
180
181 /// The canonical target endpoint of the surviving edge.
182 pub fn canon_target_id(&self) -> Uuid {
183 self.canon_target_id
184 }
185
186 /// The surviving edge's relation.
187 pub fn relation(&self) -> khive_storage::EdgeRelation {
188 self.relation
189 }
190}
191
192/// Write plan for an `update` op (entity or note shape — ADR-099 D3's
193/// `update` caveat covers both substrates the same way: row/FTS DML in the
194/// plan, any reindex deferred to `post_commit`).
195///
196/// Deferred effects are assigned by this crate's prepare pass and cannot be
197/// supplied by callers constructing a plan directly:
198///
199/// ```compile_fail
200/// use khive_runtime::{PostCommitEffect, UpdatePlan};
201/// use uuid::Uuid;
202///
203/// let id = Uuid::nil();
204/// let plan = UpdatePlan {
205/// target_id: id,
206/// statements: Vec::new(),
207/// post_commit: PostCommitEffect::ReindexEntity { entity_id: id },
208/// edge_natural_key: None,
209/// };
210/// ```
211///
212/// A plan returned by a prepare function cannot have its validated
213/// statements cleared or replaced before it reaches the runner:
214///
215/// ```compile_fail
216/// use khive_runtime::UpdatePlan;
217///
218/// fn clear_prepared_statements(mut prepared: UpdatePlan) {
219/// prepared.statements.clear();
220/// }
221/// ```
222#[derive(Debug, Clone)]
223pub struct UpdatePlan {
224 /// The id of the entity or note being updated. For a symmetric edge
225 /// update this is the CALLER's requested id — advisory only, never the
226 /// basis for post-commit result rendering (see [`EdgeNaturalKey`]).
227 pub(crate) target_id: Uuid,
228 /// Row + FTS DML statements to apply inside the atomic unit, in order.
229 /// The row-update statement carries the existence guard; any FTS-mirror
230 /// statement that follows it is unguarded (its target row's existence
231 /// was already asserted by the row-update statement's own guard).
232 pub(crate) statements: Vec<PlanStatement>,
233 /// Deferred reindex assigned by the prepare pass when the update changed
234 /// name, description, or content.
235 pub(crate) post_commit: PostCommitEffect,
236 /// `Some` only for a symmetric edge update — the natural key a caller
237 /// must use to derive the committed surviving row post-commit, rather
238 /// than trusting `target_id`. `None` for every other update shape
239 /// (entity, note, non-symmetric edge), where `target_id` alone is
240 /// already an exact, non-advisory identifier.
241 pub(crate) edge_natural_key: Option<EdgeNaturalKey>,
242}
243
244impl UpdatePlan {
245 /// The record id supplied to the prepare pass.
246 pub fn target_id(&self) -> Uuid {
247 self.target_id
248 }
249
250 /// The committed lookup key required for a symmetric edge update.
251 pub fn edge_natural_key(&self) -> Option<&EdgeNaturalKey> {
252 self.edge_natural_key.as_ref()
253 }
254
255 /// The deferred post-commit effect assigned by the prepare pass.
256 pub fn post_commit(&self) -> &PostCommitEffect {
257 &self.post_commit
258 }
259}
260
261/// Write plan for an `AddEntity` proposal change: a fresh entity row plus its
262/// FTS document in the same atomic unit. Vector indexing remains a deferred
263/// effect because embedding may suspend.
264#[derive(Debug, Clone)]
265pub struct AddEntityPlan {
266 /// The freshly generated id of the entity being created.
267 pub(crate) entity_id: Uuid,
268 /// Row + FTS insert statements to apply inside the atomic unit, in
269 /// order. The row-insert statement carries the existence guard; the
270 /// FTS-insert statement that follows it is unguarded (an ordinary
271 /// `INSERT` into a virtual table with no conflicting row).
272 pub(crate) statements: Vec<PlanStatement>,
273 /// Reindex the committed entity after the transaction closes, as
274 /// assigned by the prepare pass.
275 pub(crate) post_commit: PostCommitEffect,
276}
277
278impl AddEntityPlan {
279 /// The id generated for the prepared entity.
280 pub fn entity_id(&self) -> Uuid {
281 self.entity_id
282 }
283}
284
285/// Write plan for an `AddNote` proposal change: a fresh note row plus its FTS
286/// document in the same atomic unit.
287#[derive(Debug, Clone)]
288pub struct AddNotePlan {
289 /// The freshly generated id of the note being created.
290 pub(crate) note_id: Uuid,
291 /// Row + FTS insert statements to apply inside the atomic unit, in
292 /// order, mirroring [`AddEntityPlan::statements`].
293 pub(crate) statements: Vec<PlanStatement>,
294 /// Reindex the committed note after the transaction closes, as assigned
295 /// by the prepare pass.
296 pub(crate) post_commit: PostCommitEffect,
297}
298
299impl AddNotePlan {
300 /// The id generated for the prepared note.
301 pub fn note_id(&self) -> Uuid {
302 self.note_id
303 }
304}
305
306/// Write plan for a `delete` op (soft or hard).
307///
308/// Deferred effects are assigned by this crate's prepare pass and cannot be
309/// attached to a statement-free plan by external callers:
310///
311/// ```compile_fail
312/// use khive_runtime::{DeletePlan, PostCommitEffect};
313/// use uuid::Uuid;
314///
315/// let id = Uuid::nil();
316/// let plan = DeletePlan {
317/// target_id: id,
318/// statements: Vec::new(),
319/// post_commit: PostCommitEffect::NoteDeleted {
320/// note_id: id,
321/// kind: "observation".to_owned(),
322/// },
323/// };
324/// ```
325#[derive(Debug, Clone)]
326pub struct DeletePlan {
327 /// The id of the entity or note being deleted.
328 pub(crate) target_id: Uuid,
329 /// Row DML (and, for a hard delete, incident-edge cascade DML) to apply
330 /// inside the atomic unit, in order. The target-row delete statement
331 /// carries the existence guard; a cascade edge-delete statement (hard
332 /// delete only) is unguarded — it may legitimately affect zero rows if
333 /// the target had no incident edges.
334 pub(crate) statements: Vec<PlanStatement>,
335 /// Deferred note-mutation-hook fire assigned by the prepare pass for a
336 /// note delete (#750 2). `PostCommitEffect::None` for entity and edge
337 /// deletes — the hook system is note-only.
338 pub(crate) post_commit: PostCommitEffect,
339}
340
341impl DeletePlan {
342 /// The record id supplied to the prepare pass.
343 pub fn target_id(&self) -> Uuid {
344 self.target_id
345 }
346}
347
348/// Write plan for a `link` op (create a typed directed edge). Endpoint
349/// existence is checked **structurally**, not via an unanchored plan-level
350/// guard: `statement` is a guarded `INSERT ... SELECT ... WHERE EXISTS`
351/// shape whose `SELECT` re-probes both endpoints inside the transaction, so
352/// the runner's affected-row check on this one statement *is* the
353/// in-transaction existence probe (ADR-099 acceptance criteria's
354/// dangling-edge case — `[delete(X, hard), link(A, X)]` — is closed by this
355/// guard failing once X is gone, regardless of statement ordering
356/// convention).
357#[derive(Debug, Clone)]
358pub struct LinkPlan {
359 pub(crate) source_id: Uuid,
360 pub(crate) target_id: Uuid,
361 /// The guarded `INSERT ... SELECT ... WHERE EXISTS(...)` statement:
362 /// its affected-row count is the endpoint-existence probe.
363 pub(crate) statement: PlanStatement,
364}
365
366impl LinkPlan {
367 /// The canonical source endpoint used by the prepared statement.
368 pub fn source_id(&self) -> Uuid {
369 self.source_id
370 }
371
372 /// The canonical target endpoint used by the prepared statement.
373 pub fn target_id(&self) -> Uuid {
374 self.target_id
375 }
376}
377
378/// Write plan for a `merge` op (deduplicate two entities). Rewires and
379/// lifecycle writes are split into separate fields precisely so a guard is
380/// never ambiguous between them: the edge rewire is **predicate-based**
381/// (ADR-099 D1 rule 1) and may touch zero or many rows depending on earlier
382/// in-file writes, so it is never guarded; the `from`/`into` entity
383/// lifecycle write assumes both rows exist, so it always is.
384#[derive(Debug, Clone)]
385pub struct MergePlan {
386 pub(crate) into_id: Uuid,
387 pub(crate) from_id: Uuid,
388 /// Predicate-based edge-rewire statement(s)
389 /// (`UPDATE graph_edges SET source_id = :into WHERE source_id = :from`-
390 /// shaped), evaluated inside the transaction so they structurally see
391 /// any earlier op's edge writes in the same file (ADR-099 acceptance
392 /// criteria: "merge rewires see earlier in-file writes"). Never
393 /// guarded — a rewire touching zero rows is a legitimate outcome.
394 pub(crate) rewires: Vec<PlanPredicate>,
395 /// The `from` entity's soft-delete/tombstone DML (and any other
396 /// lifecycle write prepare assumed a target row exists for). Always
397 /// guarded — prepare validated `into`/`from` both exist.
398 pub(crate) lifecycle: Vec<PlanStatement>,
399}
400
401impl MergePlan {
402 /// The entity retained by the prepared merge.
403 pub fn into_id(&self) -> Uuid {
404 self.into_id
405 }
406
407 /// The entity retired by the prepared merge.
408 pub fn from_id(&self) -> Uuid {
409 self.from_id
410 }
411}
412
413/// Write plan for a `gtd.transition` op (explicit task lifecycle change).
414#[derive(Debug, Clone)]
415pub struct GtdTransitionPlan {
416 pub(crate) task_id: Uuid,
417 /// Task-property DML to apply inside the atomic unit. Property-only status
418 /// mutation triggers no reindex (ADR-099 D3). The transition
419 /// statement carries the guard over the exact decision snapshot's note
420 /// revision, deletion marker, and semantic status (prepare validated the
421 /// current status and requested transition were legal). For an idempotent
422 /// no-op (`current == target` after `normalize_status`) this contains one
423 /// guarded, mutation-free assertion that revalidates the prepare snapshot
424 /// under the commit transaction. Atomic v1 still persists no caller note;
425 /// canonical dispatch has a separately documented note-event path.
426 pub(crate) statements: Vec<PlanStatement>,
427 /// Explicit result-shape discriminator. A no-op can no longer be inferred
428 /// from an empty statement list because it carries a guarded assertion.
429 pub(crate) idempotent_noop: bool,
430 /// Deferred lifecycle audit row assigned by the prepare pass (GAP-5):
431 /// `PostCommitEffect::None` for the idempotent no-op case. This matches a
432 /// canonical no-op without a note; canonical note-bearing no-ops instead
433 /// attempt a same-status audit append outside atomic v1.
434 pub(crate) post_commit: PostCommitEffect,
435}
436
437impl GtdTransitionPlan {
438 /// Build a plan from its already-decided statements, no-op classification,
439 /// and audit effect.
440 /// Callers outside this crate (e.g. the atomic-apply layer wiring
441 /// `gtd.transition` into a multi-op unit) cannot construct the struct
442 /// literal directly since its fields are crate-private.
443 pub fn new(
444 task_id: Uuid,
445 statements: Vec<PlanStatement>,
446 idempotent_noop: bool,
447 post_commit: PostCommitEffect,
448 ) -> Self {
449 Self {
450 task_id,
451 statements,
452 idempotent_noop,
453 post_commit,
454 }
455 }
456
457 /// The task targeted by the prepared transition.
458 pub fn task_id(&self) -> Uuid {
459 self.task_id
460 }
461
462 /// Guarded task-property DML for this transition, or the guarded
463 /// mutation-free snapshot assertion for an idempotent no-op.
464 pub fn statements(&self) -> &[PlanStatement] {
465 &self.statements
466 }
467
468 /// Whether prepare classified this transition as already at its target.
469 pub fn is_idempotent_noop(&self) -> bool {
470 self.idempotent_noop
471 }
472
473 /// The deferred lifecycle audit effect assigned by the prepare pass.
474 pub fn post_commit(&self) -> &PostCommitEffect {
475 &self.post_commit
476 }
477}
478
479/// Write plan for a `gtd.complete` op (task lifecycle terminal transition).
480#[derive(Debug, Clone)]
481pub struct GtdCompletePlan {
482 pub(crate) task_id: Uuid,
483 /// Status + `completed_at` property DML to apply inside the atomic unit.
484 /// The statement guards the exact decision snapshot's note revision,
485 /// deletion marker, and semantic status after prepare validated that the
486 /// task was in a completable state.
487 pub(crate) statements: Vec<PlanStatement>,
488 /// Deferred lifecycle audit row assigned by the prepare pass (GAP-5):
489 /// mirrors `handle_complete`'s best-effort
490 /// `write_audit_record_with_status` call.
491 pub(crate) post_commit: PostCommitEffect,
492}
493
494impl GtdCompletePlan {
495 /// Build a plan from its already-decided statements and audit effect.
496 /// Callers outside this crate (e.g. the atomic-apply layer wiring
497 /// `gtd.complete` into a multi-op unit) cannot construct the struct
498 /// literal directly since its fields are crate-private.
499 pub fn new(
500 task_id: Uuid,
501 statements: Vec<PlanStatement>,
502 post_commit: PostCommitEffect,
503 ) -> Self {
504 Self {
505 task_id,
506 statements,
507 post_commit,
508 }
509 }
510
511 /// The task targeted by the prepared completion.
512 pub fn task_id(&self) -> Uuid {
513 self.task_id
514 }
515
516 /// Guarded status + `completed_at` property DML for this completion.
517 pub fn statements(&self) -> &[PlanStatement] {
518 &self.statements
519 }
520
521 /// The deferred lifecycle audit effect assigned by the prepare pass.
522 pub fn post_commit(&self) -> &PostCommitEffect {
523 &self.post_commit
524 }
525}
526
527/// Which governance verb (`propose` / `review` / `withdraw`) a
528/// [`GovernancePlan`] applies.
529#[derive(Debug, Clone, Copy, PartialEq, Eq)]
530pub enum GovernanceOp {
531 Propose,
532 Review,
533 Withdraw,
534}
535
536/// Write plan for a governance op (`propose`, `review`, or `withdraw` — the
537/// event-sourced change-proposal lifecycle, ADR-046).
538#[derive(Debug, Clone)]
539pub struct GovernancePlan {
540 pub(crate) op: GovernanceOp,
541 pub(crate) proposal_id: Uuid,
542 /// Event-log + status DML to apply inside the atomic unit. The
543 /// lifecycle-state-check statement carries the guard (prepare validated
544 /// the proposal was in a state admitting this transition).
545 pub(crate) statements: Vec<PlanStatement>,
546}
547
548impl GovernancePlan {
549 /// The governance operation represented by this plan.
550 pub fn op(&self) -> GovernanceOp {
551 self.op
552 }
553
554 /// The proposal targeted by this plan.
555 pub fn proposal_id(&self) -> Uuid {
556 self.proposal_id
557 }
558}
559
560#[cfg(test)]
561mod tests {
562 use super::*;
563
564 fn stmt(label: &str) -> SqlStatement {
565 SqlStatement {
566 sql: "UPDATE t SET x = ? WHERE id = ?".to_string(),
567 params: vec![],
568 label: Some(label.to_string()),
569 }
570 }
571
572 fn guarded(label: &str, guard: AffectedRowGuard) -> PlanStatement {
573 PlanStatement {
574 statement: stmt(label),
575 guard: Some(guard),
576 }
577 }
578
579 fn unguarded(label: &str) -> PlanStatement {
580 PlanStatement {
581 statement: stmt(label),
582 guard: None,
583 }
584 }
585
586 #[test]
587 fn affected_row_guard_exactly_holds_only_for_n() {
588 let g = AffectedRowGuard::exactly(1);
589 assert!(!g.holds_for(0));
590 assert!(g.holds_for(1));
591 assert!(!g.holds_for(2));
592 }
593
594 #[test]
595 fn affected_row_guard_at_least_one_has_no_upper_bound() {
596 let g = AffectedRowGuard::at_least_one();
597 assert!(!g.holds_for(0));
598 assert!(g.holds_for(1));
599 assert!(g.holds_for(1_000));
600 }
601
602 #[test]
603 fn update_plan_guard_is_anchored_to_the_row_statement_not_the_fts_mirror() {
604 let id = Uuid::new_v4();
605 let plan = UpdatePlan {
606 target_id: id,
607 statements: vec![
608 guarded("update-row", AffectedRowGuard::exactly(1)),
609 unguarded("update-fts-mirror"),
610 ],
611 post_commit: PostCommitEffect::ReindexEntity { entity_id: id },
612 edge_natural_key: None,
613 };
614 assert_eq!(plan.target_id, id);
615 assert_eq!(plan.statements[0].guard, Some(AffectedRowGuard::exactly(1)));
616 assert_eq!(plan.statements[1].guard, None);
617 assert_eq!(
618 plan.post_commit,
619 PostCommitEffect::ReindexEntity { entity_id: id }
620 );
621 }
622
623 #[test]
624 fn delete_plan_guard_is_anchored_to_the_target_row_not_the_cascade() {
625 let plan = DeletePlan {
626 target_id: Uuid::new_v4(),
627 post_commit: PostCommitEffect::None,
628 statements: vec![
629 guarded("delete-row", AffectedRowGuard::exactly(1)),
630 unguarded("cascade-edges"),
631 ],
632 };
633 let row_guard = plan.statements[0].guard.expect("row delete is guarded");
634 assert!(row_guard.holds_for(1));
635 assert!(!row_guard.holds_for(0));
636 assert_eq!(plan.statements[1].guard, None);
637 }
638
639 #[test]
640 fn link_plan_guard_is_the_endpoint_existence_probe_itself() {
641 let source = Uuid::new_v4();
642 let target = Uuid::new_v4();
643 let plan = LinkPlan {
644 source_id: source,
645 target_id: target,
646 statement: guarded("insert-edge-where-exists", AffectedRowGuard::exactly(1)),
647 };
648 assert_eq!(plan.source_id, source);
649 assert_eq!(plan.target_id, target);
650 // Dangling-edge acceptance criterion: once an endpoint row is gone,
651 // the guarded INSERT...WHERE EXISTS affects 0 rows and the guard
652 // on *that exact statement* must fail, not silently pass.
653 let guard = plan.statement.guard.expect("link insert is guarded");
654 assert!(!guard.holds_for(0));
655 }
656
657 #[test]
658 fn merge_plan_rewires_are_never_guarded_lifecycle_writes_always_are() {
659 let into = Uuid::new_v4();
660 let from = Uuid::new_v4();
661 let rewire = PlanPredicate {
662 description: "source_id = :from".to_string(),
663 statement: SqlStatement {
664 sql: "UPDATE graph_edges SET source_id = ? WHERE source_id = ?".to_string(),
665 params: vec![],
666 label: Some("merge-rewire".to_string()),
667 },
668 };
669 let plan = MergePlan {
670 into_id: into,
671 from_id: from,
672 rewires: vec![rewire],
673 lifecycle: vec![guarded(
674 "tombstone-from-entity",
675 AffectedRowGuard::exactly(1),
676 )],
677 };
678 assert_eq!(plan.into_id, into);
679 assert_eq!(plan.from_id, from);
680 assert_eq!(plan.rewires[0].description, "source_id = :from");
681 // A predicate-based rewire may legitimately touch zero or many rows
682 // depending on how many edges an earlier in-file op inserted — the
683 // type carries no guard field for it at all.
684 let lifecycle_guard = plan.lifecycle[0].guard.expect("lifecycle write is guarded");
685 assert!(!lifecycle_guard.holds_for(0));
686 }
687
688 #[test]
689 fn gtd_transition_plan_triggers_no_reindex_by_construction() {
690 let plan = GtdTransitionPlan {
691 task_id: Uuid::new_v4(),
692 statements: vec![guarded("update-status", AffectedRowGuard::exactly(1))],
693 idempotent_noop: false,
694 post_commit: PostCommitEffect::None,
695 };
696 // A status-only transition never triggers a reindex: the type has no
697 // *reindex* post-commit variant to construct, only the best-effort
698 // `GtdAudit` lifecycle-audit effect, which itself does no embedding work.
699 assert_eq!(plan.statements.len(), 1);
700 assert!(plan.statements[0].guard.is_some());
701 assert_eq!(plan.post_commit, PostCommitEffect::None);
702 }
703
704 #[test]
705 fn gtd_transition_plan_idempotent_noop_carries_guarded_assertion_and_no_audit() {
706 // Atomic v1 keeps current == target mutation-free and audit-free, but
707 // must revalidate the prepare snapshot in a multi-op unit. A canonical
708 // no-op carrying a note has a separate note-event contract.
709 let plan = GtdTransitionPlan {
710 task_id: Uuid::new_v4(),
711 statements: vec![guarded(
712 "assert-noop-snapshot",
713 AffectedRowGuard::exactly(1),
714 )],
715 idempotent_noop: true,
716 post_commit: PostCommitEffect::None,
717 };
718 assert_eq!(plan.statements.len(), 1);
719 assert!(plan.statements[0].guard.is_some());
720 assert!(plan.is_idempotent_noop());
721 assert_eq!(plan.post_commit, PostCommitEffect::None);
722 }
723
724 #[test]
725 fn gtd_transition_plan_carries_gtd_audit_post_commit_effect() {
726 let task_id = Uuid::new_v4();
727 let plan = GtdTransitionPlan {
728 task_id,
729 statements: vec![guarded("update-status", AffectedRowGuard::exactly(1))],
730 idempotent_noop: false,
731 post_commit: PostCommitEffect::GtdAudit {
732 task_id,
733 from_status: "inbox".to_string(),
734 to_status: "next".to_string(),
735 note: Some("handed off".to_string()),
736 namespace: "local".to_string(),
737 },
738 };
739 assert_eq!(
740 plan.post_commit,
741 PostCommitEffect::GtdAudit {
742 task_id,
743 from_status: "inbox".to_string(),
744 to_status: "next".to_string(),
745 note: Some("handed off".to_string()),
746 namespace: "local".to_string(),
747 }
748 );
749 }
750
751 #[test]
752 fn gtd_complete_plan_guards_the_single_snapshot_property_write() {
753 let plan = GtdCompletePlan {
754 task_id: Uuid::new_v4(),
755 statements: vec![guarded(
756 "update-status-and-completed-at",
757 AffectedRowGuard::exactly(1),
758 )],
759 post_commit: PostCommitEffect::None,
760 };
761 assert_eq!(plan.statements.len(), 1);
762 let guard = plan.statements[0]
763 .guard
764 .expect("snapshot property write is guarded");
765 assert!(guard.holds_for(1));
766 }
767
768 #[test]
769 fn governance_plan_covers_all_three_lifecycle_ops() {
770 for op in [
771 GovernanceOp::Propose,
772 GovernanceOp::Review,
773 GovernanceOp::Withdraw,
774 ] {
775 let plan = GovernancePlan {
776 op,
777 proposal_id: Uuid::new_v4(),
778 statements: vec![guarded("governance-event", AffectedRowGuard::exactly(1))],
779 };
780 assert_eq!(plan.op, op);
781 assert!(plan.statements[0].guard.is_some());
782 }
783 }
784
785 #[test]
786 fn add_entity_plan_guard_is_anchored_to_the_row_statement_not_the_fts_mirror() {
787 let id = Uuid::new_v4();
788 let plan = AddEntityPlan {
789 entity_id: id,
790 statements: vec![
791 guarded("entity-insert", AffectedRowGuard::exactly(1)),
792 unguarded("entity-fts-insert"),
793 ],
794 post_commit: PostCommitEffect::ReindexEntity { entity_id: id },
795 };
796 assert_eq!(plan.entity_id, id);
797 assert_eq!(plan.statements[0].guard, Some(AffectedRowGuard::exactly(1)));
798 assert_eq!(plan.statements[1].guard, None);
799 assert_eq!(
800 plan.post_commit,
801 PostCommitEffect::ReindexEntity { entity_id: id }
802 );
803 }
804
805 #[test]
806 fn add_note_plan_guard_is_anchored_to_the_row_statement_not_the_fts_mirror() {
807 let id = Uuid::new_v4();
808 let plan = AddNotePlan {
809 note_id: id,
810 statements: vec![
811 guarded("note-insert", AffectedRowGuard::exactly(1)),
812 unguarded("note-fts-insert"),
813 ],
814 post_commit: PostCommitEffect::ReindexNote { note_id: id },
815 };
816 assert_eq!(plan.note_id, id);
817 assert_eq!(plan.statements[0].guard, Some(AffectedRowGuard::exactly(1)));
818 assert_eq!(plan.statements[1].guard, None);
819 assert_eq!(
820 plan.post_commit,
821 PostCommitEffect::ReindexNote { note_id: id }
822 );
823 }
824
825 #[test]
826 fn plans_are_plain_data_no_async_no_embedding() {
827 // Documents a compile-time property: every plan type above derives
828 // only Debug/Clone/PartialEq, never Future or an embedding-provider
829 // trait. Plans must stay inert data: flag any edit that adds an
830 // async method or embedding-model field to one of these types.
831 let _ = PostCommitEffect::None;
832 }
833}