1use crate::{
7 DurableGraphLifecycleOptions, JsonSchemaRegistry, JsonSchemaRegistryBuilder,
8 JsonSchemaRegistryError,
9};
10use serde_json::Value;
11use stateknot_core::{
12 BoxFuture, CancellationSignal, Digest, EventId, FailureId, SchemaReference, TenantId, Version,
13};
14use stateknot_store_postgres::{
15 AgentDeadlineCancellationOutcome, AgentDeadlineCursor, PostgresStore, StoreError,
16};
17use std::{fmt, time::Duration};
18use thiserror::Error;
19
20pub const STANDARD_AGENT_DEADLINE_EVENT_SCHEMA_ID: &str =
22 "https://stknot.com/schemas/runtime/agent-deadline-event/1.0.0";
23
24pub fn standard_agent_deadline_event_schema()
26-> Result<(SchemaReference, Value), AgentDeadlineBuildError> {
27 let document: Value =
28 serde_json::from_str(include_str!("../schemas/agent-deadline-event-1.0.0.json"))
29 .map_err(|_| AgentDeadlineBuildError::SchemaDefinition)?;
30 let bytes = serde_json_canonicalizer::to_vec(&document)
31 .map_err(|_| AgentDeadlineBuildError::SchemaDefinition)?;
32 Ok((
33 SchemaReference::new(
34 STANDARD_AGENT_DEADLINE_EVENT_SCHEMA_ID
35 .parse()
36 .map_err(|_| AgentDeadlineBuildError::SchemaDefinition)?,
37 Version::new(1, 0, 0),
38 Digest::sha256(bytes),
39 ),
40 document,
41 ))
42}
43
44pub fn register_standard_agent_deadline_event_schema(
46 builder: &mut JsonSchemaRegistryBuilder,
47) -> Result<SchemaReference, AgentDeadlineBuildError> {
48 let (reference, document) = standard_agent_deadline_event_schema()?;
49 builder.register(reference.clone(), document)?;
50 Ok(reference)
51}
52
53#[derive(Debug, Error)]
55pub enum AgentDeadlineBuildError {
56 #[error("invalid embedded Agent deadline schema")]
58 SchemaDefinition,
59 #[error("Agent deadline schema is absent from the deployment registry")]
61 SchemaUnavailable,
62 #[error(transparent)]
64 Registry(#[from] JsonSchemaRegistryError),
65}
66
67#[derive(Clone, Debug)]
69pub struct AgentDeadlineSweepCursor {
70 tenant: TenantId,
71 after: Option<AgentDeadlineCursor>,
72}
73
74pub struct AgentDeadlineItem {
76 candidate: AgentDeadlineCursor,
77 result: Result<AgentDeadlineCancellationOutcome, StoreError>,
78}
79impl AgentDeadlineItem {
80 #[must_use]
82 pub const fn candidate(&self) -> &AgentDeadlineCursor {
83 &self.candidate
84 }
85 pub fn result(&self) -> Result<&AgentDeadlineCancellationOutcome, &StoreError> {
87 self.result.as_ref()
88 }
89}
90impl fmt::Debug for AgentDeadlineItem {
91 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
92 f.debug_struct("AgentDeadlineItem")
93 .field("candidate", &self.candidate)
94 .field("result", &self.result.as_ref().map_err(ToString::to_string))
95 .finish()
96 }
97}
98
99#[derive(Debug)]
101pub struct AgentDeadlineTick {
102 cursor: AgentDeadlineSweepCursor,
103 items: Vec<AgentDeadlineItem>,
104 cancelled: bool,
105}
106impl AgentDeadlineTick {
107 #[must_use]
109 pub const fn cursor(&self) -> &AgentDeadlineSweepCursor {
110 &self.cursor
111 }
112 #[must_use]
114 pub fn items(&self) -> &[AgentDeadlineItem] {
115 &self.items
116 }
117 #[must_use]
119 pub const fn is_cancelled(&self) -> bool {
120 self.cancelled
121 }
122}
123
124#[derive(Clone, Debug)]
152pub struct DurableAgentDeadlineReconciler {
153 store: PostgresStore,
154 schemas: JsonSchemaRegistry,
155 schema: SchemaReference,
156 options: DurableGraphLifecycleOptions,
157}
158impl DurableAgentDeadlineReconciler {
159 pub fn new(
161 store: PostgresStore,
162 schemas: JsonSchemaRegistry,
163 options: DurableGraphLifecycleOptions,
164 ) -> Result<Self, AgentDeadlineBuildError> {
165 let (schema, _) = standard_agent_deadline_event_schema()?;
166 if !schemas.contains(&schema) {
167 return Err(AgentDeadlineBuildError::SchemaUnavailable);
168 }
169 Ok(Self {
170 store,
171 schemas,
172 schema,
173 options,
174 })
175 }
176 pub fn tick(
179 &self,
180 tenant: TenantId,
181 after: Option<AgentDeadlineSweepCursor>,
182 shutdown: CancellationSignal,
183 ) -> BoxFuture<'_, Result<AgentDeadlineTick, StoreError>> {
184 Box::pin(async move {
185 if after.as_ref().is_some_and(|cursor| cursor.tenant != tenant) {
186 return Err(StoreError::InvalidAgentDeadline);
187 }
188 let mut tick = AgentDeadlineTick {
189 cursor: after.unwrap_or(AgentDeadlineSweepCursor {
190 tenant: tenant.clone(),
191 after: None,
192 }),
193 items: Vec::with_capacity(16),
194 cancelled: false,
195 };
196 let candidates = tokio::select! {
197 biased;
198 () = shutdown.cancelled() => { tick.cancelled=true; return Ok(tick); }
199 candidates = self.store.due_agent_deadlines_after(&tenant,tick.cursor.after.as_ref()) => candidates?,
200 };
201 let exhausted = candidates.len() < 16;
202 for candidate in candidates {
203 let result = tokio::select! {
204 biased;
205 () = shutdown.cancelled() => { tick.cancelled=true; break; }
206 result = self.request_with_retry(&candidate) => result,
207 };
208 tick.cursor.after = Some(candidate.clone());
209 tick.items.push(AgentDeadlineItem { candidate, result });
210 }
211 if exhausted && !tick.cancelled {
212 tick.cursor.after = None;
213 }
214 Ok(tick)
215 })
216 }
217
218 async fn request_with_retry(
219 &self,
220 candidate: &AgentDeadlineCursor,
221 ) -> Result<AgentDeadlineCancellationOutcome, StoreError> {
222 let event = EventId::generate();
223 let failure = FailureId::generate();
224 for attempt in 1..=self.options.maximum_mutation_attempts() {
225 let result = self
226 .store
227 .request_agent_deadline_cancellation(
228 candidate.tenant_id(),
229 candidate.run_id(),
230 event,
231 failure,
232 &self.schema,
233 &self.schemas,
234 )
235 .await;
236 match result {
237 Err(error)
238 if error.is_retryable()
239 && attempt < self.options.maximum_mutation_attempts() =>
240 {
241 let delay = self
242 .options
243 .mutation_retry_initial_delay()
244 .saturating_mul(1_u32 << (attempt - 1))
245 .min(Duration::from_secs(1));
246 tokio::time::sleep(delay).await;
247 }
248 other => return other,
249 }
250 }
251 unreachable!("validated positive retry bound")
252 }
253}
254
255#[cfg(test)]
256mod tests {
257 use super::*;
258 use crate::JsonSchemaRegistryLimits;
259 use stateknot_core::BoundedJson;
260
261 #[test]
262 fn deadline_schema_is_offline_closed_and_exactly_pinned() {
263 let mut builder = JsonSchemaRegistryBuilder::new(JsonSchemaRegistryLimits::default());
264 let reference = register_standard_agent_deadline_event_schema(&mut builder).unwrap();
265 assert_eq!(reference, standard_agent_deadline_event_schema().unwrap().0);
266 let registry = builder.build().unwrap();
267 let mut value = serde_json::json!({"operation":"agent_deadline_cancellation_requested",
268 "admission_digest":"a".repeat(64),"deadline":"2026-09-09T12:00:00.000000Z","failure_id":FailureId::generate().to_string()});
269 registry
270 .validate_bounded(
271 &reference,
272 &BoundedJson::try_from_value(value.clone()).unwrap(),
273 )
274 .unwrap();
275 value["output"] = serde_json::json!({"must_not_leak":true});
276 assert!(
277 registry
278 .validate_bounded(&reference, &BoundedJson::try_from_value(value).unwrap())
279 .is_err()
280 );
281 }
282}