Skip to main content

stateknot_runtime/
cancellation_schema.rs

1// Copyright 2026 StateKnot contributors
2// SPDX-License-Identifier: Apache-2.0
3
4//! Versioned public-safe journal schema for durable cancellation acknowledgement.
5
6use serde_json::Value;
7use stateknot_core::{Digest, SchemaId, SchemaIdError, SchemaReference, Version};
8use thiserror::Error;
9
10use crate::{JsonSchemaRegistryBuilder, JsonSchemaRegistryError};
11
12/// Stable identity of the v1 agent cancellation event-data schema.
13pub const STANDARD_AGENT_CANCELLATION_EVENT_SCHEMA_ID: &str =
14    "https://stknot.com/schemas/runtime/agent-cancellation-event/1.0.0";
15
16const DOCUMENT: &str = include_str!("../schemas/agent-cancellation-event-1.0.0.json");
17
18/// Returns the immutable reference and owned JSON Schema document shipped with
19/// this runtime release.
20///
21/// # Errors
22///
23/// Returns [`StandardAgentCancellationSchemaError`] only when the embedded
24/// release artifact is internally malformed.
25pub fn standard_agent_cancellation_event_schema()
26-> Result<(SchemaReference, Value), StandardAgentCancellationSchemaError> {
27    let document = serde_json::from_str::<Value>(DOCUMENT)
28        .map_err(|_| StandardAgentCancellationSchemaError::EmbeddedDocument)?;
29    let canonical = serde_json_canonicalizer::to_vec(&document)
30        .map_err(|_| StandardAgentCancellationSchemaError::Canonicalization)?;
31    let id = STANDARD_AGENT_CANCELLATION_EVENT_SCHEMA_ID
32        .parse::<SchemaId>()
33        .map_err(StandardAgentCancellationSchemaError::identifier)?;
34    let reference = SchemaReference::new(id, Version::new(1, 0, 0), Digest::sha256(canonical));
35    Ok((reference, document))
36}
37
38/// Registers the standard agent cancellation event schema in a startup registry.
39///
40/// # Errors
41///
42/// Returns an embedded-definition error or the registry's duplicate, resource,
43/// dialect, digest, and reference-resolution failures.
44pub fn register_standard_agent_cancellation_event_schema(
45    builder: &mut JsonSchemaRegistryBuilder,
46) -> Result<SchemaReference, StandardAgentCancellationSchemaRegistrationError> {
47    let (reference, document) = standard_agent_cancellation_event_schema()?;
48    builder.register(reference.clone(), document)?;
49    Ok(reference)
50}
51
52/// Internal release-artifact failure for the embedded standard schema.
53#[derive(Clone, Debug, Eq, Error, PartialEq)]
54#[non_exhaustive]
55pub enum StandardAgentCancellationSchemaError {
56    /// The embedded JSON document cannot be parsed.
57    #[error("embedded agent cancellation event schema is invalid JSON")]
58    EmbeddedDocument,
59    /// The embedded document cannot be represented as RFC 8785 bytes.
60    #[error("embedded agent cancellation event schema cannot be canonicalized")]
61    Canonicalization,
62    /// The embedded stable HTTPS identifier is invalid.
63    #[error("embedded agent cancellation event schema identifier is invalid: {source}")]
64    Identifier {
65        /// Exact identifier validation error.
66        #[source]
67        source: SchemaIdError,
68    },
69}
70
71impl StandardAgentCancellationSchemaError {
72    const fn identifier(source: SchemaIdError) -> Self {
73        Self::Identifier { source }
74    }
75}
76
77/// Startup failure while adding the standard cancellation schema to a registry.
78#[derive(Clone, Debug, Eq, Error, PartialEq)]
79#[non_exhaustive]
80pub enum StandardAgentCancellationSchemaRegistrationError {
81    /// The embedded release artifact was malformed.
82    #[error(transparent)]
83    Definition(#[from] StandardAgentCancellationSchemaError),
84    /// The target registry rejected the immutable resource.
85    #[error(transparent)]
86    Registry(#[from] JsonSchemaRegistryError),
87}
88
89#[cfg(test)]
90mod tests {
91    use super::*;
92    use crate::JsonSchemaRegistryLimits;
93    use serde_json::json;
94    use stateknot_core::BoundedJson;
95
96    #[test]
97    fn standard_schema_is_digest_pinned_and_registry_valid() {
98        let (reference, document) = standard_agent_cancellation_event_schema().unwrap();
99        assert_eq!(
100            reference.id().as_str(),
101            STANDARD_AGENT_CANCELLATION_EVENT_SCHEMA_ID
102        );
103        assert_eq!(reference.version(), Version::new(1, 0, 0));
104
105        let mut builder = JsonSchemaRegistryBuilder::new(JsonSchemaRegistryLimits::default());
106        builder.register(reference.clone(), document).unwrap();
107        let registry = builder.build().unwrap();
108        assert!(registry.contains(&reference));
109    }
110
111    #[test]
112    fn standard_schema_accepts_only_the_closed_confirmation_shape() {
113        let (reference, document) = standard_agent_cancellation_event_schema().unwrap();
114        let mut builder = JsonSchemaRegistryBuilder::new(JsonSchemaRegistryLimits::default());
115        builder.register(reference.clone(), document).unwrap();
116        let registry = builder.build().unwrap();
117        let valid = json!({
118            "operation": "agent_cancellation_confirmed",
119            "graph_digest": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
120            "checkpoint_id": "01912345-6789-7abc-8def-0123456789ab",
121            "superstep": "1",
122            "failure_id": "01912345-6789-7abc-8def-0123456789ac"
123        });
124        registry
125            .validate_bounded(
126                &reference,
127                &BoundedJson::try_from_value(valid.clone()).unwrap(),
128            )
129            .unwrap();
130
131        let mut leaked = valid;
132        leaked["usage"] = json!({"model_turns": 1});
133        assert!(
134            registry
135                .validate_bounded(&reference, &BoundedJson::try_from_value(leaked).unwrap())
136                .is_err()
137        );
138    }
139}