Skip to main content

stateknot_store_postgres/
child_cancellation.rs

1// Copyright 2026 StateKnot contributors
2// SPDX-License-Identifier: Apache-2.0
3
4//! Bounded durable cancellation delivery. Delivery never confirms a terminal outcome.
5
6#[allow(clippy::wildcard_imports)]
7use super::*;
8use child_runs::{ancestry, anchored_event, load_record_inner, lock_tree, row_head};
9use stateknot_core::{ChildRunKey, RunCancellationRequest};
10
11/// What the child had durably observed when its cancellation work was consumed.
12#[derive(Clone, Copy, Debug, Eq, PartialEq)]
13pub enum ChildCancellationOutcome {
14    /// This transaction requested cancellation; execution cleanup is still required.
15    Requested,
16    /// Another cancellation already owned the child; its reason was not overwritten.
17    AlreadyRequested,
18    /// The child was already terminal; its outcome and accounting were not changed.
19    Terminal,
20}
21
22impl ChildCancellationOutcome {
23    const fn text(self) -> &'static str {
24        match self {
25            Self::Requested => "requested",
26            Self::AlreadyRequested => "already_requested",
27            Self::Terminal => "terminal",
28        }
29    }
30}
31
32/// Immutable delivery evidence; not acknowledgement that external work stopped.
33#[derive(Clone, Debug)]
34pub struct ChildCancellationReceipt {
35    outcome: ChildCancellationOutcome,
36    lifecycle: RunLifecycle,
37    head: JournalHead,
38    delivered_at: Timestamp,
39}
40
41impl ChildCancellationReceipt {
42    /// Returns whether cancellation was newly requested, already requested, or unnecessary.
43    #[must_use]
44    pub const fn outcome(&self) -> ChildCancellationOutcome {
45        self.outcome
46    }
47    /// Returns the captured child lifecycle, not a later mutable projection.
48    #[must_use]
49    pub const fn lifecycle(&self) -> &RunLifecycle {
50        &self.lifecycle
51    }
52    /// Returns the exact child journal observation retained after later appends.
53    #[must_use]
54    pub const fn head(&self) -> &JournalHead {
55        &self.head
56    }
57    /// Returns the database observation that consumed queue work.
58    #[must_use]
59    pub const fn delivered_at(&self) -> Timestamp {
60        self.delivered_at
61    }
62}
63
64/// Verified immutable parent cancellation witness and optional child delivery receipt.
65#[derive(Clone, Debug)]
66pub struct ChildCancellationRecord {
67    key: ChildRunKey,
68    child_run_id: RunId,
69    parent_lifecycle: RunLifecycle,
70    parent_head: JournalHead,
71    queued_at: Timestamp,
72    receipt: Option<ChildCancellationReceipt>,
73}
74
75impl ChildCancellationRecord {
76    /// True when the source is a sealed failure, not user cancellation.
77    #[must_use]
78    pub fn is_parent_failure_close(&self) -> bool {
79        self.parent_lifecycle.status() == RunStatus::Active
80    }
81    /// Returns the exact tenant/parent activation/slot ownership key.
82    #[must_use]
83    pub const fn key(&self) -> &ChildRunKey {
84        &self.key
85    }
86    /// Returns the immutable owned child identity.
87    #[must_use]
88    pub const fn child_run_id(&self) -> RunId {
89        self.child_run_id
90    }
91    /// Returns the captured parent cancellation lifecycle.
92    #[must_use]
93    pub const fn parent_lifecycle(&self) -> &RunLifecycle {
94        &self.parent_lifecycle
95    }
96    /// Returns the source observation, possibly a later audit head for upgraded work.
97    #[must_use]
98    pub const fn parent_head(&self) -> &JournalHead {
99        &self.parent_head
100    }
101    /// Returns queue insertion time; scan order is not a permanent delivery watermark.
102    #[must_use]
103    pub const fn queued_at(&self) -> Timestamp {
104        self.queued_at
105    }
106    /// Returns the original once-only delivery evidence.
107    #[must_use]
108    pub const fn receipt(&self) -> Option<&ChildCancellationReceipt> {
109        self.receipt.as_ref()
110    }
111}
112
113/// Atomic delivery result, with original evidence recovered on logical retries.
114#[derive(Clone, Debug)]
115pub enum ChildCancellationDelivery {
116    /// Child request/abandonment, descendant queue work and receipt committed together.
117    Committed(ChildCancellationRecord),
118    /// This ownership key was already delivered; no child mutation was repeated.
119    Idempotent(ChildCancellationRecord),
120}
121
122impl ChildCancellationDelivery {
123    /// Returns verified original delivery evidence for either outcome.
124    #[must_use]
125    pub const fn record(&self) -> &ChildCancellationRecord {
126        match self {
127            Self::Committed(value) | Self::Idempotent(value) => value,
128        }
129    }
130}
131
132impl PostgresStore {
133    /// Loads a cancellation witness and verifies its ownership, lifecycle and exact anchors.
134    /// Authentication and tenant delegation authorization must precede this trusted-store API.
135    pub async fn load_child_cancellation(
136        &self,
137        key: &ChildRunKey,
138    ) -> Result<ChildCancellationRecord, StoreError> {
139        Box::pin(self.load_child_cancellation_inner(key)).await
140    }
141
142    async fn load_child_cancellation_inner(
143        &self,
144        key: &ChildRunKey,
145    ) -> Result<ChildCancellationRecord, StoreError> {
146        let mut tx = self
147            .begin_repeatable_read("child cancellation read")
148            .await?;
149        let parent = query_as::<_, RunRow>(SELECT_RUN)
150            .bind(key.tenant_id().as_str())
151            .bind(*key.parent_run_id().as_uuid())
152            .fetch_optional(&mut *tx)
153            .await
154            .map_err(|source| StoreError::database("child cancellation parent", source))?
155            .ok_or(StoreError::ChildCancellationNotFound)?;
156        let parent = decode_run(parent)?;
157        let child = Box::pin(load_record_inner(&mut tx, key, false))
158            .await?
159            .ok_or(StoreError::ChildRunNotFound)?;
160        let record = load_cancellation(&mut tx, key, &parent, &child).await?;
161        tx.commit()
162            .await
163            .map_err(|source| StoreError::database("child cancellation read commit", source))?;
164        Ok(record)
165    }
166
167    /// Discovers at most 16 pending cancellation keys using an index range.
168    /// Continue with the last key, even after delivery; restart at `None` after a full sweep.
169    /// A full sweep must pass blocked/quarantined items; never retain an event-time watermark.
170    pub async fn pending_child_cancellations_after(
171        &self,
172        tenant: &TenantId,
173        after: Option<&ChildRunKey>,
174    ) -> Result<Vec<ChildRunKey>, StoreError> {
175        let cursor = if let Some(key) = after {
176            if key.tenant_id() != tenant {
177                return Err(StoreError::ChildRunRejected);
178            }
179            Some(query_as::<_, (DateTime<Utc>, Uuid)>("SELECT queued_at, child_run_id FROM stateknot.child_run_cancellations WHERE tenant_id=$1 AND parent_run_id=$2 AND key_digest=$3")
180                .bind(tenant.as_str()).bind(*key.parent_run_id().as_uuid()).bind(key.digest().as_bytes())
181                .fetch_optional(&self.pool).await.map_err(|source| StoreError::database("child cancellation cursor", source))?
182                .ok_or(StoreError::ChildCancellationNotFound)?)
183        } else {
184            None
185        };
186        let sql = if cursor.is_some() {
187            "SELECT owner.key_bytes, work.key_digest, work.parent_run_id FROM stateknot.child_run_cancellations AS work JOIN stateknot.child_run_ownership AS owner USING (tenant_id,parent_run_id,key_digest,child_run_id) WHERE work.tenant_id=$1 AND work.delivered_at IS NULL AND (work.queued_at,work.child_run_id)>($2,$3) ORDER BY work.queued_at,work.child_run_id LIMIT 16"
188        } else {
189            "SELECT owner.key_bytes, work.key_digest, work.parent_run_id FROM stateknot.child_run_cancellations AS work JOIN stateknot.child_run_ownership AS owner USING (tenant_id,parent_run_id,key_digest,child_run_id) WHERE work.tenant_id=$1 AND work.delivered_at IS NULL ORDER BY work.queued_at,work.child_run_id LIMIT 16"
190        };
191        let mut listing = query_as::<_, (Vec<u8>, Vec<u8>, Uuid)>(sql).bind(tenant.as_str());
192        if let Some((at, child)) = cursor {
193            listing = listing.bind(at).bind(child);
194        }
195        let rows = listing
196            .fetch_all(&self.pool)
197            .await
198            .map_err(|source| StoreError::database("child cancellation discovery", source))?;
199        rows.into_iter()
200            .map(|(bytes, digest, parent)| {
201                if bytes.len() > 65_536 {
202                    return Err(StoreError::corrupt("child cancellation key size"));
203                }
204                let key: ChildRunKey = serde_json::from_slice(&bytes)
205                    .map_err(|_| StoreError::corrupt("child cancellation key"))?;
206                if key.tenant_id() != tenant
207                    || *key.parent_run_id().as_uuid() != parent
208                    || key.digest() != decode_digest(&digest, "child cancellation key checksum")?
209                {
210                    return Err(StoreError::corrupt("child cancellation key scope"));
211                }
212                Ok(key)
213            })
214            .collect()
215    }
216
217    /// Delivers a parent's durable cancellation to one owned child in one transaction.
218    /// Locks tree → parent → child. Child request, all existing wait abandonments,
219    /// descendant work and immutable receipt commit together. No external code runs here.
220    /// Existing child cancellation/terminal outcomes win without replacement. Logical
221    /// retries recover the first receipt before checking candidate IDs or stale heads.
222    /// This trusted control-plane operation never confirms cancellation or invents usage.
223    #[allow(clippy::too_many_lines)]
224    pub async fn deliver_child_cancellation(
225        &self,
226        key: &ChildRunKey,
227        append: JournalAppend,
228        request: RunCancellationRequest,
229    ) -> Result<ChildCancellationDelivery, StoreError> {
230        if append.worker_fence().is_some()
231            || append.intent().tenant_id() != key.tenant_id()
232            || append.intent().payload().kind().as_str() != "child-run-cancellation-requested"
233            || request.failure().caused_by_event_id() != Some(append.intent().event_id())
234        {
235            return Err(StoreError::ChildRunRejected);
236        }
237        let mut tx = self.begin_mutation("child cancellation delivery").await?;
238        let ancestors = ancestry(&mut tx, key.tenant_id(), key.parent_run_id()).await?;
239        lock_tree(&mut tx, key.tenant_id(), ancestors[0]).await?;
240        let parent =
241            decode_run(fetch_locked_run_row(&mut tx, key.tenant_id(), key.parent_run_id()).await?)?;
242        let child = Box::pin(load_record_inner(&mut tx, key, true))
243            .await?
244            .ok_or(StoreError::ChildRunNotFound)?;
245        let record = load_cancellation(&mut tx, key, &parent, &child).await?;
246        if append.intent().run_id() != record.child_run_id {
247            return Err(StoreError::ChildRunRejected);
248        }
249        if record.receipt.is_some() {
250            tx.commit()
251                .await
252                .map_err(|source| StoreError::database("child cancellation retry", source))?;
253            return Ok(ChildCancellationDelivery::Idempotent(record));
254        }
255        if parent.is_quarantined() || child.child().run().is_quarantined() {
256            return Err(StoreError::RunQuarantined);
257        }
258        let current = child.child().run();
259        let mut at = database_now(&mut tx, "child cancellation clock")
260            .await?
261            .max(record.queued_at);
262        let (outcome, lifecycle, head) = if current.lifecycle().status().is_terminal() {
263            (
264                ChildCancellationOutcome::Terminal,
265                current.lifecycle().clone(),
266                current
267                    .journal_head()
268                    .cloned()
269                    .ok_or(StoreError::ChildRunRejected)?,
270            )
271        } else if current.lifecycle().cancellation_request().is_some() {
272            (
273                ChildCancellationOutcome::AlreadyRequested,
274                current.lifecycle().clone(),
275                current
276                    .journal_head()
277                    .cloned()
278                    .ok_or(StoreError::ChildRunRejected)?,
279            )
280        } else {
281            if failure_closes::exists(&mut tx, key.tenant_id(), record.child_run_id).await? {
282                return Err(StoreError::RunFailureClosing);
283            }
284            if append.expectation().head() != current.journal_head() {
285                return Err(StoreError::StaleJournalHead);
286            }
287            at = at.max(
288                current
289                    .journal_head()
290                    .ok_or(StoreError::ChildRunRejected)?
291                    .recorded_at(),
292            );
293            if request.requested_at() < record.parent_lifecycle.changed_at() {
294                return Err(StoreError::ChildRunRejected);
295            }
296            let transition = RunTransition::RequestCancellation { request };
297            let projection =
298                RunProjection::transition(current.lifecycle().revision(), transition.clone());
299            let prepared = prepare_durable_wait_projection(
300                current,
301                key.tenant_id(),
302                record.child_run_id,
303                current.lifecycle().revision(),
304                transition.clone(),
305                at,
306            )?;
307            let lifecycle = current
308                .lifecycle()
309                .clone()
310                .apply(transition)
311                .map_err(|_| StoreError::InvalidLifecycleTransition)?;
312            verify_current_wait_set(&mut tx, current).await?;
313            let waits = cancellation_waits(&mut tx, current).await?;
314            let digest = if waits.is_empty() {
315                projection_digest(&projection)?
316            } else {
317                wait_abandonment_projection_digest(&projection, &waits)?
318            };
319            let event =
320                JournalEvent::commit(append, at).map_err(|error| map_event_commit_error(&error))?;
321            insert_event(&mut tx, &event, digest).await?;
322            for wait in waits {
323                let abandonment = materialize_wait_abandonment(
324                    wait,
325                    WaitAbandonmentReason::RunCancellation,
326                    event.head(),
327                )?;
328                insert_wait_abandonment(&mut tx, &abandonment).await?;
329                project_wait_abandonment(&mut tx, &abandonment).await?;
330            }
331            update_run_head(&mut tx, &event, Some(&prepared)).await?;
332            (ChildCancellationOutcome::Requested, lifecycle, event.head())
333        };
334        at = at.max(head.recorded_at());
335        let bytes = encode_lifecycle(&lifecycle)?;
336        query("INSERT INTO stateknot.child_run_cancellation_receipts (tenant_id,parent_run_id,key_digest,child_run_id,outcome,lifecycle_bytes,lifecycle_digest,journal_sequence,journal_event_id,journal_recorded_at,journal_digest,delivered_at) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12)")
337            .bind(key.tenant_id().as_str()).bind(*key.parent_run_id().as_uuid()).bind(key.digest().as_bytes()).bind(*record.child_run_id.as_uuid())
338            .bind(outcome.text()).bind(&bytes).bind(Digest::sha256(&bytes).as_bytes())
339            .bind(i64::try_from(head.sequence().get()).map_err(|_| StoreError::JournalSequenceExhausted)?)
340            .bind(*head.event_id().as_uuid()).bind(to_database_time(head.recorded_at())?).bind(head.digest().as_bytes()).bind(to_database_time(at)?)
341            .execute(&mut *tx).await.map_err(|source| StoreError::database("child cancellation receipt insert", source))?;
342        let updated = query("UPDATE stateknot.child_run_cancellations SET delivered_at=$4 WHERE tenant_id=$1 AND parent_run_id=$2 AND key_digest=$3 AND delivered_at IS NULL")
343            .bind(key.tenant_id().as_str()).bind(*key.parent_run_id().as_uuid()).bind(key.digest().as_bytes()).bind(to_database_time(at)?)
344            .execute(&mut *tx).await.map_err(|source| StoreError::database("child cancellation delivery projection", source))?.rows_affected();
345        if updated != 1 {
346            return Err(StoreError::corrupt("child cancellation delivery row count"));
347        }
348        let mut record = record;
349        record.receipt = Some(ChildCancellationReceipt {
350            outcome,
351            lifecycle,
352            head,
353            delivered_at: at,
354        });
355        tx.commit()
356            .await
357            .map_err(|source| StoreError::database("child cancellation delivery commit", source))?;
358        Ok(ChildCancellationDelivery::Committed(record))
359    }
360}
361
362pub(super) async fn cancellation_waits(
363    tx: &mut Transaction<'_, Postgres>,
364    stored: &StoredRun,
365) -> Result<Vec<DurableWait>, StoreError> {
366    if stored.lifecycle().status() != RunStatus::Waiting {
367        return Ok(Vec::new());
368    }
369    let scope = stored.lifecycle().provenance();
370    let rows = query_as::<_, WaitRegistrationRow>(
371        SELECT_OUTSTANDING_WAIT_REGISTRATIONS_FOR_UPDATE.as_str(),
372    )
373    .bind(scope.tenant_id().as_str())
374    .bind(*scope.run_id().as_uuid())
375    .fetch_all(&mut **tx)
376    .await
377    .map_err(|source| StoreError::database("child cancellation wait lock", source))?;
378    if rows.is_empty()
379        || rows.len() > RunWaits::MAX_LEN
380        || rows.len() != usize::from(stored.unresolved_wait_count())
381    {
382        return Err(StoreError::WaitAbandonmentCommitConflict);
383    }
384    let mut waits = Vec::with_capacity(rows.len());
385    for row in rows {
386        let wait = decode_wait_registration(&row)?;
387        if row.status != "outstanding" {
388            return Err(StoreError::WaitAbandonmentCommitConflict);
389        }
390        verify_wait_registration_event(tx, &wait, row.registration_sequence).await?;
391        waits.push(wait);
392    }
393    Ok(waits)
394}
395
396fn get_error(source: sqlx_core::Error) -> StoreError {
397    StoreError::database("child cancellation decode", source)
398}
399
400fn lifecycle_from_row(row: &PgRow) -> Result<RunLifecycle, StoreError> {
401    let bytes: Vec<u8> = row.try_get("lifecycle_bytes").map_err(get_error)?;
402    if bytes.is_empty() || bytes.len() > 4_194_304 {
403        return Err(StoreError::corrupt("child cancellation lifecycle size"));
404    }
405    let lifecycle: RunLifecycle = serde_json::from_slice(&bytes)
406        .map_err(|_| StoreError::corrupt("child cancellation lifecycle"))?;
407    if encode_lifecycle(&lifecycle)? != bytes
408        || Digest::sha256(&bytes)
409            != decode_digest(
410                &row.try_get::<Vec<u8>, _>("lifecycle_digest")
411                    .map_err(get_error)?,
412                "child cancellation lifecycle checksum",
413            )?
414    {
415        return Err(StoreError::corrupt("child cancellation lifecycle checksum"));
416    }
417    Ok(lifecycle)
418}
419
420async fn verify_head(
421    tx: &mut Transaction<'_, Postgres>,
422    head: &JournalHead,
423) -> Result<(JournalEvent, Option<Digest>), StoreError> {
424    let event = anchored_event(
425        tx,
426        head.tenant_id(),
427        head.run_id(),
428        i64::try_from(head.sequence().get())
429            .map_err(|_| StoreError::corrupt("child cancellation sequence"))?,
430    )
431    .await?;
432    if event.0.head() != *head {
433        return Err(StoreError::corrupt("child cancellation journal anchor"));
434    }
435    Ok(event)
436}
437
438fn cancellation_matches(left: &RunLifecycle, right: &RunLifecycle) -> Result<bool, StoreError> {
439    let encode = |value: &RunLifecycle| {
440        serde_json_canonicalizer::to_vec(&value.cancellation_request())
441            .map_err(|_| StoreError::corrupt("child cancellation request encoding"))
442    };
443    Ok(encode(left)? == encode(right)?)
444}
445
446#[allow(clippy::too_many_lines)]
447async fn load_cancellation(
448    tx: &mut Transaction<'_, Postgres>,
449    key: &ChildRunKey,
450    parent: &StoredRun,
451    child: &ChildRunRecord,
452) -> Result<ChildCancellationRecord, StoreError> {
453    let row = query("SELECT * FROM stateknot.child_run_cancellations WHERE tenant_id=$1 AND parent_run_id=$2 AND key_digest=$3")
454        .bind(key.tenant_id().as_str()).bind(*key.parent_run_id().as_uuid()).bind(key.digest().as_bytes()).fetch_optional(&mut **tx).await
455        .map_err(|source| StoreError::database("child cancellation witness", source))?.ok_or(StoreError::ChildCancellationNotFound)?;
456    let lifecycle = lifecycle_from_row(&row)?;
457    let head = row_head(&row, key.tenant_id(), key.parent_run_id())?;
458    verify_head(tx, &head).await?;
459    let child_id = child.child().admission().intent().provenance().run_id();
460    let queued_at = from_database_time(row.try_get("queued_at").map_err(get_error)?)?;
461    let delivered: Option<DateTime<Utc>> = row.try_get("delivered_at").map_err(get_error)?;
462    let valid_source = if lifecycle.status() == RunStatus::Active {
463        let close = failure_closes::load(tx, parent)
464            .await?
465            .ok_or_else(|| StoreError::corrupt("child failure close source"))?;
466        close.registration().head() == head
467            && encode_lifecycle(close.lifecycle())? == encode_lifecycle(&lifecycle)?
468    } else {
469        lifecycle.status() == RunStatus::CancellationRequested
470            && cancellation_matches(&lifecycle, parent.lifecycle())?
471    };
472    if row.try_get::<Uuid, _>("child_run_id").map_err(get_error)? != *child_id.as_uuid()
473        || !valid_source
474        || lifecycle.provenance() != parent.lifecycle().provenance()
475        || parent.lifecycle().revision() < lifecycle.revision()
476        || parent
477            .journal_head()
478            .is_none_or(|current| current.sequence() < head.sequence())
479        || lifecycle.changed_at() > head.recorded_at()
480        || head.sequence() <= child.spawn().sequence()
481    {
482        return Err(StoreError::corrupt("child cancellation parent binding"));
483    }
484    let receipt_row = query("SELECT * FROM stateknot.child_run_cancellation_receipts WHERE tenant_id=$1 AND parent_run_id=$2 AND key_digest=$3")
485        .bind(key.tenant_id().as_str()).bind(*key.parent_run_id().as_uuid()).bind(key.digest().as_bytes()).fetch_optional(&mut **tx).await
486        .map_err(|source| StoreError::database("child cancellation receipt", source))?;
487    if delivered.is_some() != receipt_row.is_some() {
488        return Err(StoreError::corrupt(
489            "child cancellation delivery projection",
490        ));
491    }
492    let receipt = if let Some(row) = receipt_row {
493        let captured = lifecycle_from_row(&row)?;
494        let receipt_head = row_head(&row, key.tenant_id(), child_id)?;
495        let (event, projection) = verify_head(tx, &receipt_head).await?;
496        let delivered_at = from_database_time(row.try_get("delivered_at").map_err(get_error)?)?;
497        let outcome = match row
498            .try_get::<String, _>("outcome")
499            .map_err(get_error)?
500            .as_str()
501        {
502            "requested" => ChildCancellationOutcome::Requested,
503            "already_requested" => ChildCancellationOutcome::AlreadyRequested,
504            "terminal" => ChildCancellationOutcome::Terminal,
505            _ => return Err(StoreError::corrupt("child cancellation receipt outcome")),
506        };
507        let current = child.child().run();
508        if row.try_get::<Uuid, _>("child_run_id").map_err(get_error)? != *child_id.as_uuid()
509            || captured.provenance() != current.lifecycle().provenance()
510            || captured.revision() > current.lifecycle().revision()
511            || captured.changed_at() > receipt_head.recorded_at()
512            || current
513                .journal_head()
514                .is_none_or(|value| value.sequence() < receipt_head.sequence())
515            || delivered != Some(to_database_time(delivered_at)?)
516            || delivered_at < queued_at
517            || delivered_at < receipt_head.recorded_at()
518        {
519            return Err(StoreError::corrupt("child cancellation receipt binding"));
520        }
521        match outcome {
522            ChildCancellationOutcome::Terminal => {
523                if !captured.status().is_terminal()
524                    || encode_lifecycle(&captured)? != encode_lifecycle(current.lifecycle())?
525                {
526                    return Err(StoreError::corrupt("child cancellation terminal receipt"));
527                }
528            }
529            ChildCancellationOutcome::Requested | ChildCancellationOutcome::AlreadyRequested => {
530                if captured.status() != RunStatus::CancellationRequested
531                    || !cancellation_matches(&captured, current.lifecycle())?
532                {
533                    return Err(StoreError::corrupt("child cancellation request receipt"));
534                }
535                if outcome == ChildCancellationOutcome::Requested {
536                    let request = captured
537                        .cancellation_request()
538                        .ok_or(StoreError::ChildRunRejected)?;
539                    if request.failure().caused_by_event_id() != Some(receipt_head.event_id())
540                        || event.payload().kind().as_str() != "child-run-cancellation-requested"
541                        || !matches!(event.source(), JournalEventSource::ControlPlane)
542                    {
543                        return Err(StoreError::corrupt("child cancellation delivered event"));
544                    }
545                    let previous = captured
546                        .revision()
547                        .get()
548                        .checked_sub(1)
549                        .ok_or(StoreError::ChildRunRejected)?;
550                    let transition = RunProjection::transition(
551                        RunRevision::new(previous),
552                        RunTransition::RequestCancellation {
553                            request: request.clone(),
554                        },
555                    );
556                    let abandonments = load_wait_abandonment_set_or_empty(tx, &event).await?;
557                    if abandonments
558                        .iter()
559                        .any(|value| value.reason() != WaitAbandonmentReason::RunCancellation)
560                    {
561                        return Err(StoreError::corrupt("child cancellation wait reason"));
562                    }
563                    let waits = abandonments
564                        .into_iter()
565                        .map(|value| value.wait().clone())
566                        .collect::<Vec<_>>();
567                    let expected = if waits.is_empty() {
568                        projection_digest(&transition)?
569                    } else {
570                        wait_abandonment_projection_digest(&transition, &waits)?
571                    };
572                    if projection != Some(expected) {
573                        return Err(StoreError::corrupt("child cancellation request projection"));
574                    }
575                }
576            }
577        }
578        Some(ChildCancellationReceipt {
579            outcome,
580            lifecycle: captured,
581            head: receipt_head,
582            delivered_at,
583        })
584    } else {
585        None
586    };
587    Ok(ChildCancellationRecord {
588        key: key.clone(),
589        child_run_id: child_id,
590        parent_lifecycle: lifecycle,
591        parent_head: head,
592        queued_at,
593        receipt,
594    })
595}
596
597pub(super) async fn verify_schema(pool: &PgPool) -> Result<(), StoreError> {
598    let complete = query_scalar::<_, bool>(r"SELECT
599      NOT EXISTS (SELECT 1 FROM (VALUES
600        ('runs_child_cancellation_capture','stateknot.runs','stateknot.capture_child_run_cancellation()',17),
601        ('runs_child_cancellation_claim_guard','stateknot.runs','stateknot.guard_child_cancellation_claim()',19),
602        ('child_cancellations_immutable','stateknot.child_run_cancellations','stateknot.guard_child_cancellation_evidence()',27),
603        ('child_cancellation_receipts_immutable','stateknot.child_run_cancellation_receipts','stateknot.guard_child_cancellation_evidence()',27)
604      ) AS expected(name,relation,function,mask) WHERE NOT EXISTS (SELECT 1 FROM pg_trigger WHERE tgname=expected.name AND tgrelid=to_regclass(expected.relation) AND tgfoid=to_regprocedure(expected.function) AND tgtype=expected.mask AND tgenabled='O' AND NOT tgisinternal))
605      AND NOT EXISTS (SELECT 1 FROM (VALUES
606        ('child_run_cancellations_owner_fk','stateknot.child_run_cancellations','FOREIGN KEY (tenant_id, parent_run_id, key_digest, child_run_id) REFERENCES stateknot.child_run_ownership(tenant_id, parent_run_id, key_digest, child_run_id) ON DELETE RESTRICT'),
607        ('child_run_cancellations_event_fk','stateknot.child_run_cancellations','FOREIGN KEY (tenant_id, parent_run_id, journal_sequence, journal_event_id, journal_recorded_at, journal_digest) REFERENCES stateknot.run_events(tenant_id, run_id, sequence, event_id, recorded_at, event_digest) ON DELETE RESTRICT'),
608        ('child_run_cancellation_receipts_source_fk','stateknot.child_run_cancellation_receipts','FOREIGN KEY (tenant_id, parent_run_id, key_digest, child_run_id) REFERENCES stateknot.child_run_cancellations(tenant_id, parent_run_id, key_digest, child_run_id) ON DELETE RESTRICT'),
609        ('child_run_cancellation_receipts_event_fk','stateknot.child_run_cancellation_receipts','FOREIGN KEY (tenant_id, child_run_id, journal_sequence, journal_event_id, journal_recorded_at, journal_digest) REFERENCES stateknot.run_events(tenant_id, run_id, sequence, event_id, recorded_at, event_digest) ON DELETE RESTRICT'),
610        ('child_run_cancellations_pkey','stateknot.child_run_cancellations','PRIMARY KEY (tenant_id, parent_run_id, key_digest)'),
611        ('child_run_cancellations_child_unique','stateknot.child_run_cancellations','UNIQUE (tenant_id, child_run_id)'),
612        ('child_run_cancellations_exact_unique','stateknot.child_run_cancellations','UNIQUE (tenant_id, parent_run_id, key_digest, child_run_id)'),
613        ('child_run_cancellation_receipts_pkey','stateknot.child_run_cancellation_receipts','PRIMARY KEY (tenant_id, parent_run_id, key_digest)'),
614        ('child_run_cancellation_receipts_child_unique','stateknot.child_run_cancellation_receipts','UNIQUE (tenant_id, child_run_id)'),
615        ('child_run_cancellations_check','stateknot.child_run_cancellations','CHECK ((lifecycle_digest = sha256(lifecycle_bytes)))'),
616        ('child_run_cancellation_receipts_check','stateknot.child_run_cancellation_receipts','CHECK ((lifecycle_digest = sha256(lifecycle_bytes)))'),
617        ('child_run_cancellations_key_digest_check','stateknot.child_run_cancellations','CHECK ((octet_length(key_digest) = 32))'),
618        ('child_run_cancellations_lifecycle_bytes_check','stateknot.child_run_cancellations','CHECK (((octet_length(lifecycle_bytes) >= 1) AND (octet_length(lifecycle_bytes) <= 4194304)))'),
619        ('child_run_cancellation_receipts_lifecycle_bytes_check','stateknot.child_run_cancellation_receipts','CHECK (((octet_length(lifecycle_bytes) >= 1) AND (octet_length(lifecycle_bytes) <= 4194304)))'),
620        ('child_run_cancellation_receipts_outcome_check','stateknot.child_run_cancellation_receipts','CHECK ((outcome = ANY (ARRAY[''requested''::text, ''already_requested''::text, ''terminal''::text])))'),
621        ('child_run_cancellations_clock_valid','stateknot.child_run_cancellations','CHECK (((delivered_at IS NULL) OR (delivered_at >= queued_at)))')
622      ) AS expected(name,relation,definition) WHERE NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname=expected.name AND conrelid=to_regclass(expected.relation) AND convalidated AND NOT condeferrable AND pg_get_constraintdef(oid)=expected.definition))
623      AND EXISTS (SELECT 1 FROM pg_index WHERE indexrelid=to_regclass('stateknot.child_run_cancellations_pending') AND indrelid=to_regclass('stateknot.child_run_cancellations') AND indisvalid AND indisready AND indislive AND pg_get_indexdef(indexrelid)='CREATE INDEX child_run_cancellations_pending ON stateknot.child_run_cancellations USING btree (tenant_id, queued_at, child_run_id) WHERE (delivered_at IS NULL)')")
624        .fetch_one(pool).await.map_err(|source| StoreError::database("child cancellation schema", source))?;
625    if !complete {
626        return Err(StoreError::IncompleteSchema);
627    }
628    for function in include_str!("../migrations/0021_child_run_cancellation.sql")
629        .split("CREATE FUNCTION stateknot.")
630        .skip(1)
631    {
632        let (name, _) = function
633            .split_once("() RETURNS trigger")
634            .ok_or(StoreError::IncompleteSchema)?;
635        let body = function
636            .split("$$")
637            .nth(1)
638            .ok_or(StoreError::IncompleteSchema)?;
639        let installed = query_scalar::<_, String>("SELECT prosrc FROM pg_proc JOIN pg_language ON pg_language.oid=prolang WHERE pg_proc.oid=to_regprocedure($1) AND NOT prosecdef AND lanname='plpgsql'")
640            .bind(format!("stateknot.{name}()")).fetch_optional(pool).await.map_err(|source| StoreError::database("child cancellation guard", source))?;
641        if installed.as_deref() != Some(body) {
642            return Err(StoreError::IncompleteSchema);
643        }
644    }
645    Ok(())
646}