1use std::collections::BTreeMap;
7
8use schemars::JsonSchema;
9use serde::{Deserialize, Deserializer, Serialize, de};
10use thiserror::Error;
11
12use crate::{
13 AgentDescriptor, CapabilityIdentity, ChildRunAdmissionIntent, ChildRunSlot, CompiledGraph,
14 Digest, GraphReference, NodeId, SchemaReference,
15};
16
17#[derive(Clone, Debug, Deserialize, Eq, JsonSchema, PartialEq, Serialize)]
23#[serde(deny_unknown_fields)]
24pub struct ChildAgentReference {
25 identity: CapabilityIdentity,
26 definition_digest: Digest,
27}
28
29impl ChildAgentReference {
30 pub fn from_descriptor(descriptor: &AgentDescriptor) -> Result<Self, ChildRunPolicyError> {
32 let canonical = crate::agent_admission::canonical_bytes(descriptor)
33 .map_err(|_| ChildRunPolicyError::AgentEncoding)?;
34 let mut bytes = b"stateknot.child-agent-definition.v1\0".to_vec();
35 bytes.extend_from_slice(&canonical);
36 Ok(Self {
37 identity: descriptor.metadata().identity().clone(),
38 definition_digest: Digest::sha256(bytes),
39 })
40 }
41
42 #[must_use]
44 pub const fn identity(&self) -> &CapabilityIdentity {
45 &self.identity
46 }
47
48 #[must_use]
50 pub const fn definition_digest(&self) -> Digest {
51 self.definition_digest
52 }
53}
54
55#[derive(Clone, Debug, Deserialize, Eq, JsonSchema, PartialEq, Serialize)]
57#[serde(deny_unknown_fields)]
58pub struct ChildRunDeclaration {
59 node_id: NodeId,
60 slot: ChildRunSlot,
61 agent: ChildAgentReference,
62 graph: GraphReference,
63 input_schema: SchemaReference,
64 output_schema: SchemaReference,
65}
66
67impl ChildRunDeclaration {
68 pub fn new(
70 node_id: NodeId,
71 slot: ChildRunSlot,
72 agent: &AgentDescriptor,
73 graph: &CompiledGraph,
74 ) -> Result<Self, ChildRunPolicyError> {
75 if agent.input_schema() != graph.input_schema()
76 || agent.output_schema() != graph.output_schema()
77 {
78 return Err(ChildRunPolicyError::TargetSchemaMismatch);
79 }
80 Ok(Self {
81 node_id,
82 slot,
83 agent: ChildAgentReference::from_descriptor(agent)?,
84 graph: graph.reference(),
85 input_schema: agent.input_schema().clone(),
86 output_schema: agent.output_schema().clone(),
87 })
88 }
89
90 #[must_use]
92 pub const fn node_id(&self) -> &NodeId {
93 &self.node_id
94 }
95
96 #[must_use]
98 pub const fn slot(&self) -> &ChildRunSlot {
99 &self.slot
100 }
101
102 #[must_use]
104 pub const fn agent(&self) -> &ChildAgentReference {
105 &self.agent
106 }
107
108 #[must_use]
110 pub const fn graph(&self) -> &GraphReference {
111 &self.graph
112 }
113
114 #[must_use]
116 pub const fn input_schema(&self) -> &SchemaReference {
117 &self.input_schema
118 }
119
120 #[must_use]
122 pub const fn output_schema(&self) -> &SchemaReference {
123 &self.output_schema
124 }
125
126 pub fn validate_target(
132 &self,
133 target: &CompiledGraph,
134 limits: ChildRunTopologyLimits,
135 ) -> Result<(), ChildRunPolicyError> {
136 if &target.reference() != self.graph() {
137 return Err(ChildRunPolicyError::TargetGraphMismatch);
138 }
139 if target.input_schema() != self.input_schema()
140 || target.output_schema() != self.output_schema()
141 {
142 return Err(ChildRunPolicyError::TargetSchemaMismatch);
143 }
144 let child_depth = target
145 .child_runs()
146 .map_or(0, |policy| policy.limits().maximum_descendant_depth());
147 if child_depth >= limits.maximum_descendant_depth() {
148 return Err(ChildRunPolicyError::DepthNotNarrowed);
149 }
150 Ok(())
151 }
152}
153
154#[derive(Clone, Copy, Debug, Eq, JsonSchema, PartialEq, Serialize)]
161#[serde(deny_unknown_fields)]
162#[allow(clippy::struct_field_names)]
164pub struct ChildRunTopologyLimits {
165 #[schemars(range(min = 1, max = 32))]
166 maximum_descendant_depth: u16,
167 #[schemars(range(min = 1, max = 256))]
168 maximum_children_per_run: u16,
169 #[schemars(range(min = 1, max = 256))]
170 maximum_active_descendants: u16,
171}
172
173impl ChildRunTopologyLimits {
174 pub const MAX_DEPTH: u16 = 32;
176 pub const MAX_CHILDREN: u16 = 256;
178
179 pub fn new(depth: u16, children: u16, active: u16) -> Result<Self, ChildRunPolicyError> {
181 if !(1..=Self::MAX_DEPTH).contains(&depth)
182 || !(1..=Self::MAX_CHILDREN).contains(&children)
183 || !(1..=Self::MAX_CHILDREN).contains(&active)
184 {
185 return Err(ChildRunPolicyError::InvalidLimits);
186 }
187 Ok(Self {
188 maximum_descendant_depth: depth,
189 maximum_children_per_run: children,
190 maximum_active_descendants: active,
191 })
192 }
193
194 #[must_use]
196 pub const fn maximum_descendant_depth(self) -> u16 {
197 self.maximum_descendant_depth
198 }
199
200 #[must_use]
202 pub const fn maximum_children_per_run(self) -> u16 {
203 self.maximum_children_per_run
204 }
205
206 #[must_use]
208 pub const fn maximum_active_descendants(self) -> u16 {
209 self.maximum_active_descendants
210 }
211}
212
213impl<'de> Deserialize<'de> for ChildRunTopologyLimits {
214 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
215 #[derive(Deserialize)]
216 #[serde(deny_unknown_fields)]
217 #[allow(clippy::struct_field_names)]
218 struct Wire {
219 maximum_descendant_depth: u16,
220 maximum_children_per_run: u16,
221 maximum_active_descendants: u16,
222 }
223 let wire = Wire::deserialize(deserializer)?;
224 Self::new(
225 wire.maximum_descendant_depth,
226 wire.maximum_children_per_run,
227 wire.maximum_active_descendants,
228 )
229 .map_err(de::Error::custom)
230 }
231}
232
233#[derive(Clone, Debug, Eq, JsonSchema, PartialEq, Serialize)]
240#[serde(deny_unknown_fields)]
241pub struct GraphChildRunPolicy {
242 #[schemars(range(min = 1, max = 1))]
243 version: u8,
244 limits: ChildRunTopologyLimits,
245 #[schemars(length(min = 1, max = 256))]
246 declarations: Box<[ChildRunDeclaration]>,
247}
248
249impl GraphChildRunPolicy {
250 pub const MAX_DECLARATIONS: usize = 256;
252 pub const MAX_SLOTS_PER_NODE: usize = 64;
254
255 pub fn new<I>(
257 limits: ChildRunTopologyLimits,
258 declarations: I,
259 ) -> Result<Self, ChildRunPolicyError>
260 where
261 I: IntoIterator<Item = ChildRunDeclaration>,
262 {
263 let mut ordered = BTreeMap::new();
264 let mut per_node = BTreeMap::new();
265 for declaration in declarations {
266 if ordered.len() == Self::MAX_DECLARATIONS {
267 return Err(ChildRunPolicyError::TooManyDeclarations);
268 }
269 let count = per_node.entry(declaration.node_id.clone()).or_insert(0);
270 *count += 1;
271 if *count > Self::MAX_SLOTS_PER_NODE {
272 return Err(ChildRunPolicyError::TooManyNodeSlots);
273 }
274 let key = (declaration.node_id.clone(), declaration.slot.clone());
275 if ordered.insert(key, declaration).is_some() {
276 return Err(ChildRunPolicyError::DuplicateSlot);
277 }
278 }
279 if ordered.is_empty() {
280 return Err(ChildRunPolicyError::EmptyDeclarations);
281 }
282 Ok(Self {
283 version: 1,
284 limits,
285 declarations: ordered.into_values().collect(),
286 })
287 }
288
289 #[must_use]
291 pub const fn limits(&self) -> ChildRunTopologyLimits {
292 self.limits
293 }
294
295 #[must_use]
297 pub const fn declarations(&self) -> &[ChildRunDeclaration] {
298 &self.declarations
299 }
300
301 #[must_use]
303 pub fn declaration(&self, node: &NodeId, slot: &ChildRunSlot) -> Option<&ChildRunDeclaration> {
304 self.declarations
305 .binary_search_by(|value| (&value.node_id, &value.slot).cmp(&(node, slot)))
306 .ok()
307 .map(|index| &self.declarations[index])
308 }
309
310 pub(crate) fn validate_nodes(&self, graph: &CompiledGraph) -> Result<(), ChildRunPolicyError> {
311 if self
312 .declarations
313 .iter()
314 .any(|item| graph.node(item.node_id()).is_none())
315 {
316 return Err(ChildRunPolicyError::UndeclaredParentNode);
317 }
318 Ok(())
319 }
320}
321
322impl<'de> Deserialize<'de> for GraphChildRunPolicy {
323 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
324 #[derive(Deserialize)]
325 #[serde(deny_unknown_fields)]
326 struct Wire {
327 version: u8,
328 limits: ChildRunTopologyLimits,
329 #[serde(deserialize_with = "bounded_declarations")]
330 declarations: Vec<ChildRunDeclaration>,
331 }
332 let wire = Wire::deserialize(deserializer)?;
333 if wire.version != 1 {
334 return Err(de::Error::custom(ChildRunPolicyError::UnsupportedVersion));
335 }
336 Self::new(wire.limits, wire.declarations).map_err(de::Error::custom)
337 }
338}
339
340fn bounded_declarations<'de, D: Deserializer<'de>>(
341 deserializer: D,
342) -> Result<Vec<ChildRunDeclaration>, D::Error> {
343 struct Visitor;
344 impl<'de> de::Visitor<'de> for Visitor {
345 type Value = Vec<ChildRunDeclaration>;
346
347 fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
348 formatter.write_str("at most 256 child declarations")
349 }
350
351 fn visit_seq<A: de::SeqAccess<'de>>(
352 self,
353 mut sequence: A,
354 ) -> Result<Self::Value, A::Error> {
355 let maximum = GraphChildRunPolicy::MAX_DECLARATIONS;
356 if sequence.size_hint().is_some_and(|size| size > maximum) {
357 return Err(de::Error::custom(ChildRunPolicyError::TooManyDeclarations));
358 }
359 let mut values = Vec::with_capacity(sequence.size_hint().unwrap_or(0).min(maximum));
360 while let Some(value) = sequence.next_element()? {
361 if values.len() == maximum {
362 return Err(de::Error::custom(ChildRunPolicyError::TooManyDeclarations));
363 }
364 values.push(value);
365 }
366 Ok(values)
367 }
368 }
369 deserializer.deserialize_seq(Visitor)
370}
371
372impl ChildRunAdmissionIntent {
373 pub fn validate_declaration(&self, parent: &CompiledGraph) -> Result<(), ChildRunPolicyError> {
379 if self.key().parent().base_checkpoint().graph() != &parent.reference() {
380 return Err(ChildRunPolicyError::ParentGraphMismatch);
381 }
382 let policy = parent
383 .child_runs()
384 .ok_or(ChildRunPolicyError::DelegationNotDeclared)?;
385 let declaration = policy
386 .declaration(self.key().parent().node_id(), self.key().slot())
387 .ok_or(ChildRunPolicyError::DelegationNotDeclared)?;
388 declaration.validate_target(self.child_graph(), policy.limits())?;
389 if declaration.agent() != &ChildAgentReference::from_descriptor(self.child().descriptor())?
390 {
391 return Err(ChildRunPolicyError::TargetAgentMismatch);
392 }
393 Ok(())
394 }
395}
396
397#[derive(Clone, Debug, Eq, Error, PartialEq)]
399#[non_exhaustive]
400pub enum ChildRunPolicyError {
401 #[error("child Agent definition encoding failed")]
403 AgentEncoding,
404 #[error("invalid child topology limits")]
406 InvalidLimits,
407 #[error("child policy must declare at least one slot")]
409 EmptyDeclarations,
410 #[error("too many graph child declarations")]
412 TooManyDeclarations,
413 #[error("too many child slots on one node")]
415 TooManyNodeSlots,
416 #[error("duplicate child slot on one node")]
418 DuplicateSlot,
419 #[error("unsupported child policy version")]
421 UnsupportedVersion,
422 #[error("child declaration references an unknown parent node")]
424 UndeclaredParentNode,
425 #[error("child declaration parent graph mismatch")]
427 ParentGraphMismatch,
428 #[error("child delegation is not declared by the parent node")]
430 DelegationNotDeclared,
431 #[error("declared child graph mismatch")]
433 TargetGraphMismatch,
434 #[error("declared child input or output schema mismatch")]
436 TargetSchemaMismatch,
437 #[error("declared child Agent definition mismatch")]
439 TargetAgentMismatch,
440 #[error("declared child depth does not narrow the parent depth")]
442 DepthNotNarrowed,
443}
444
445#[cfg(test)]
446#[path = "child_run_policy_tests.rs"]
447mod tests;