1use std::{fmt, str::FromStr};
14
15use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema};
16use serde::{Deserialize, Deserializer, Serialize, Serializer, de};
17use thiserror::Error;
18
19use crate::decimal::{UnsignedDecimalError, parse_bounded_u64};
20use crate::{
21 AttemptId, ByteCount, Checkpoint, CheckpointHead, Digest, ExecutionCount, InvocationId,
22 JournalHead, JournalSequence, NodeId, RetryAdvice, RunId, TenantId, Timestamp, ToolDescriptor,
23 ToolError, ToolExecutionLimits, ToolExternalEffect, ToolInput, ToolResult, ToolRisk,
24};
25
26const MAX_DATABASE_ORDINAL: u64 = i64::MAX as u64;
27const INVOCATION_REVISION_PATTERN: &str = "^(0|[1-9][0-9]{0,18})$";
28const GRAPH_NAMESPACE_PATTERN: &str =
29 "^(?:[A-Za-z0-9][A-Za-z0-9_.-]{0,127}(?:/[A-Za-z0-9][A-Za-z0-9_.-]{0,127})*)?$";
30const READY_NODE_INPUT_DIGEST_DOMAIN: &[u8] = b"stateknot-ready-node-input-v1\0";
31const INTENT_DIGEST_DOMAIN: &[u8] = b"stateknot-tool-invocation-intent-v1\0";
32const TRANSITION_DIGEST_DOMAIN: &[u8] = b"stateknot-tool-invocation-transition-v1\0";
33const RECORD_DIGEST_DOMAIN: &[u8] = b"stateknot-tool-invocation-record-v1\0";
34
35#[derive(Clone, Eq, Hash, Ord, PartialEq, PartialOrd)]
41pub struct GraphNamespace(Box<str>);
42
43impl GraphNamespace {
44 pub const MAX_LEN: usize = 512;
46
47 #[must_use]
49 pub fn root() -> Self {
50 Self(Box::from(""))
51 }
52
53 pub fn new(value: impl Into<String>) -> Result<Self, GraphNamespaceError> {
60 let value = value.into();
61 if value.len() > Self::MAX_LEN {
62 return Err(GraphNamespaceError::TooLong {
63 maximum: Self::MAX_LEN,
64 actual: value.len(),
65 });
66 }
67 if value.is_empty() {
68 return Ok(Self::root());
69 }
70 for (index, segment) in value.split('/').enumerate() {
71 NodeId::new(segment)
72 .map_err(|source| GraphNamespaceError::InvalidSegment { index, source })?;
73 }
74 Ok(Self(value.into_boxed_str()))
75 }
76
77 #[must_use]
79 pub fn as_str(&self) -> &str {
80 &self.0
81 }
82
83 #[must_use]
85 pub fn is_root(&self) -> bool {
86 self.0.is_empty()
87 }
88}
89
90impl Default for GraphNamespace {
91 fn default() -> Self {
92 Self::root()
93 }
94}
95
96impl AsRef<str> for GraphNamespace {
97 fn as_ref(&self) -> &str {
98 self.as_str()
99 }
100}
101
102impl fmt::Debug for GraphNamespace {
103 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
104 formatter
105 .debug_tuple("GraphNamespace")
106 .field(&self.as_str())
107 .finish()
108 }
109}
110
111impl fmt::Display for GraphNamespace {
112 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
113 formatter.write_str(self.as_str())
114 }
115}
116
117impl FromStr for GraphNamespace {
118 type Err = GraphNamespaceError;
119
120 fn from_str(value: &str) -> Result<Self, Self::Err> {
121 Self::new(value)
122 }
123}
124
125impl TryFrom<String> for GraphNamespace {
126 type Error = GraphNamespaceError;
127
128 fn try_from(value: String) -> Result<Self, Self::Error> {
129 Self::new(value)
130 }
131}
132
133impl TryFrom<&str> for GraphNamespace {
134 type Error = GraphNamespaceError;
135
136 fn try_from(value: &str) -> Result<Self, Self::Error> {
137 Self::new(value)
138 }
139}
140
141impl Serialize for GraphNamespace {
142 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
143 where
144 S: Serializer,
145 {
146 serializer.serialize_str(self.as_str())
147 }
148}
149
150impl<'de> Deserialize<'de> for GraphNamespace {
151 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
152 where
153 D: Deserializer<'de>,
154 {
155 deserializer.deserialize_string(GraphNamespaceVisitor)
156 }
157}
158
159struct GraphNamespaceVisitor;
160
161impl de::Visitor<'_> for GraphNamespaceVisitor {
162 type Value = GraphNamespace;
163
164 fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
165 formatter.write_str("a root or slash-separated bounded graph namespace")
166 }
167
168 fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
169 where
170 E: de::Error,
171 {
172 GraphNamespace::try_from(value).map_err(E::custom)
173 }
174
175 fn visit_string<E>(self, value: String) -> Result<Self::Value, E>
176 where
177 E: de::Error,
178 {
179 GraphNamespace::try_from(value).map_err(E::custom)
180 }
181}
182
183impl JsonSchema for GraphNamespace {
184 fn schema_name() -> std::borrow::Cow<'static, str> {
185 "GraphNamespace".into()
186 }
187
188 fn schema_id() -> std::borrow::Cow<'static, str> {
189 concat!(module_path!(), "::GraphNamespace").into()
190 }
191
192 fn json_schema(_: &mut SchemaGenerator) -> Schema {
193 json_schema!({
194 "type": "string",
195 "maxLength": 512,
196 "pattern": GRAPH_NAMESPACE_PATTERN,
197 "description": "The empty string is the root graph. Runtime additionally rejects '.' and '..' segments."
198 })
199 }
200
201 fn inline_schema() -> bool {
202 true
203 }
204}
205
206#[derive(Clone, Debug, Eq, Error, PartialEq)]
208#[non_exhaustive]
209pub enum GraphNamespaceError {
210 #[error("graph namespace is {actual} bytes; maximum is {maximum}")]
212 TooLong {
213 maximum: usize,
215 actual: usize,
217 },
218 #[error("graph namespace segment {index} is invalid: {source}")]
220 InvalidSegment {
221 index: usize,
223 #[source]
225 source: crate::NodeIdError,
226 },
227}
228
229#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
234pub struct ToolInvocationRevision(u64);
235
236impl ToolInvocationRevision {
237 pub const INITIAL: Self = Self(0);
239 pub const MAX: Self = Self(MAX_DATABASE_ORDINAL);
241
242 pub const fn new(value: u64) -> Result<Self, ToolInvocationRevisionError> {
249 if value > MAX_DATABASE_ORDINAL {
250 return Err(ToolInvocationRevisionError::AboveMaximum);
251 }
252 Ok(Self(value))
253 }
254
255 #[must_use]
257 pub const fn get(self) -> u64 {
258 self.0
259 }
260
261 #[must_use]
263 pub const fn checked_next(self) -> Option<Self> {
264 if self.0 == MAX_DATABASE_ORDINAL {
265 None
266 } else {
267 Some(Self(self.0 + 1))
268 }
269 }
270}
271
272impl fmt::Display for ToolInvocationRevision {
273 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
274 self.0.fmt(formatter)
275 }
276}
277
278impl FromStr for ToolInvocationRevision {
279 type Err = ToolInvocationRevisionError;
280
281 fn from_str(value: &str) -> Result<Self, Self::Err> {
282 let value = parse_bounded_u64(value, MAX_DATABASE_ORDINAL)
283 .map_err(ToolInvocationRevisionError::from_decimal_error)?;
284 Self::new(value)
285 }
286}
287
288impl Serialize for ToolInvocationRevision {
289 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
290 where
291 S: Serializer,
292 {
293 serializer.collect_str(self)
294 }
295}
296
297impl<'de> Deserialize<'de> for ToolInvocationRevision {
298 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
299 where
300 D: Deserializer<'de>,
301 {
302 deserializer.deserialize_str(ToolInvocationRevisionVisitor)
303 }
304}
305
306struct ToolInvocationRevisionVisitor;
307
308impl de::Visitor<'_> for ToolInvocationRevisionVisitor {
309 type Value = ToolInvocationRevision;
310
311 fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
312 formatter.write_str("a canonical non-negative decimal PostgreSQL BIGINT revision")
313 }
314
315 fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
316 where
317 E: de::Error,
318 {
319 value.parse().map_err(E::custom)
320 }
321}
322
323impl JsonSchema for ToolInvocationRevision {
324 fn schema_name() -> std::borrow::Cow<'static, str> {
325 "ToolInvocationRevision".into()
326 }
327
328 fn schema_id() -> std::borrow::Cow<'static, str> {
329 concat!(module_path!(), "::ToolInvocationRevision").into()
330 }
331
332 fn json_schema(_: &mut SchemaGenerator) -> Schema {
333 json_schema!({
334 "type": "string",
335 "minLength": 1,
336 "maxLength": 19,
337 "pattern": INVOCATION_REVISION_PATTERN
338 })
339 }
340
341 fn inline_schema() -> bool {
342 true
343 }
344}
345
346#[derive(Clone, Debug, Eq, Error, PartialEq)]
348#[non_exhaustive]
349pub enum ToolInvocationRevisionError {
350 #[error("tool invocation revision must contain only unsigned ASCII decimal digits")]
352 InvalidFormat,
353 #[error("tool invocation revision must use canonical decimal text")]
355 NonCanonical,
356 #[error("tool invocation revision exceeds the PostgreSQL BIGINT maximum")]
358 AboveMaximum,
359}
360
361impl ToolInvocationRevisionError {
362 const fn from_decimal_error(error: UnsignedDecimalError) -> Self {
363 match error {
364 UnsignedDecimalError::Empty | UnsignedDecimalError::InvalidCharacter { .. } => {
365 Self::InvalidFormat
366 }
367 UnsignedDecimalError::LeadingZero => Self::NonCanonical,
368 UnsignedDecimalError::TooLong { .. } | UnsignedDecimalError::Overflow => {
369 Self::AboveMaximum
370 }
371 }
372 }
373}
374
375#[derive(Clone, Debug, Deserialize, Eq, JsonSchema, PartialEq, Serialize)]
381#[serde(deny_unknown_fields)]
382pub struct NodeActivation {
383 base_checkpoint: CheckpointHead,
384 graph_namespace: GraphNamespace,
385 node_id: NodeId,
386 input_digest: Digest,
387}
388
389impl NodeActivation {
390 #[must_use]
392 pub const fn new(
393 base_checkpoint: CheckpointHead,
394 graph_namespace: GraphNamespace,
395 node_id: NodeId,
396 input_digest: Digest,
397 ) -> Self {
398 Self {
399 base_checkpoint,
400 graph_namespace,
401 node_id,
402 input_digest,
403 }
404 }
405
406 pub fn for_ready_root(
421 checkpoint: &Checkpoint,
422 node_id: NodeId,
423 ) -> Result<Self, NodeActivationError> {
424 if !checkpoint.ready_nodes().contains(&node_id) {
425 return Err(NodeActivationError::NodeNotReady { node_id });
426 }
427 let graph_namespace = GraphNamespace::root();
428 let input_digest =
429 compute_ready_node_input_digest(checkpoint.digest(), &graph_namespace, &node_id)?;
430 Ok(Self::new(
431 checkpoint.head(),
432 graph_namespace,
433 node_id,
434 input_digest,
435 ))
436 }
437
438 #[must_use]
440 pub const fn base_checkpoint(&self) -> &CheckpointHead {
441 &self.base_checkpoint
442 }
443
444 #[must_use]
446 pub const fn graph_namespace(&self) -> &GraphNamespace {
447 &self.graph_namespace
448 }
449
450 #[must_use]
452 pub const fn node_id(&self) -> &NodeId {
453 &self.node_id
454 }
455
456 #[must_use]
458 pub const fn input_digest(&self) -> Digest {
459 self.input_digest
460 }
461
462 #[must_use]
464 pub const fn tenant_id(&self) -> &TenantId {
465 self.base_checkpoint.tenant_id()
466 }
467
468 #[must_use]
470 pub const fn run_id(&self) -> RunId {
471 self.base_checkpoint.run_id()
472 }
473}
474
475#[derive(Clone, Debug, Eq, Error, PartialEq)]
477#[non_exhaustive]
478pub enum NodeActivationError {
479 #[error("node {node_id:?} is not ready in the base checkpoint")]
481 NodeNotReady {
482 node_id: NodeId,
484 },
485 #[error("ready-node activation input canonical serialization failed")]
487 CanonicalSerialization,
488}
489
490#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, JsonSchema, PartialEq, Serialize)]
492#[non_exhaustive]
493#[serde(rename_all = "snake_case")]
494pub enum ToolInvocationLimit {
495 Timeout,
497 MaxConcurrency,
499 MaxInputBytes,
501 MaxInlineResultBytes,
503 MaxArtifacts,
505 MaxTotalArtifactBytes,
507}
508
509#[derive(Clone, Eq, JsonSchema, PartialEq, Serialize)]
511#[serde(deny_unknown_fields)]
512pub struct ToolInvocationIntent {
513 activation: NodeActivation,
514 invocation_id: InvocationId,
515 descriptor: ToolDescriptor,
516 input: ToolInput,
517 effective_limits: ToolExecutionLimits,
518 intent_digest: Digest,
519}
520
521impl ToolInvocationIntent {
522 pub fn new(
533 activation: NodeActivation,
534 invocation_id: InvocationId,
535 descriptor: ToolDescriptor,
536 input: ToolInput,
537 effective_limits: ToolExecutionLimits,
538 ) -> Result<Self, ToolInvocationIntentError> {
539 validate_intent_shape(&descriptor, &input, &effective_limits)?;
540 let intent_digest = compute_intent_digest(&ToolInvocationIntentDigestWire {
541 activation: &activation,
542 invocation_id,
543 descriptor: &descriptor,
544 input: &input,
545 effective_limits: &effective_limits,
546 })?;
547 Ok(Self {
548 activation,
549 invocation_id,
550 descriptor,
551 input,
552 effective_limits,
553 intent_digest,
554 })
555 }
556
557 pub fn restore(
563 activation: NodeActivation,
564 invocation_id: InvocationId,
565 descriptor: ToolDescriptor,
566 input: ToolInput,
567 effective_limits: ToolExecutionLimits,
568 intent_digest: Digest,
569 ) -> Result<Self, ToolInvocationIntentError> {
570 let restored = Self::new(
571 activation,
572 invocation_id,
573 descriptor,
574 input,
575 effective_limits,
576 )?;
577 if restored.intent_digest != intent_digest {
578 return Err(ToolInvocationIntentError::DigestMismatch);
579 }
580 Ok(restored)
581 }
582
583 #[must_use]
585 pub const fn activation(&self) -> &NodeActivation {
586 &self.activation
587 }
588
589 #[must_use]
591 pub const fn invocation_id(&self) -> InvocationId {
592 self.invocation_id
593 }
594
595 #[must_use]
597 pub const fn descriptor(&self) -> &ToolDescriptor {
598 &self.descriptor
599 }
600
601 #[must_use]
603 pub const fn input(&self) -> &ToolInput {
604 &self.input
605 }
606
607 #[must_use]
609 pub const fn effective_limits(&self) -> &ToolExecutionLimits {
610 &self.effective_limits
611 }
612
613 #[must_use]
615 pub const fn intent_digest(&self) -> Digest {
616 self.intent_digest
617 }
618
619 #[must_use]
621 pub const fn tenant_id(&self) -> &TenantId {
622 self.activation.tenant_id()
623 }
624
625 #[must_use]
627 pub const fn run_id(&self) -> RunId {
628 self.activation.run_id()
629 }
630}
631
632impl fmt::Debug for ToolInvocationIntent {
633 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
634 formatter
635 .debug_struct("ToolInvocationIntent")
636 .field("activation", &self.activation)
637 .field("invocation_id", &self.invocation_id)
638 .field("descriptor", &self.descriptor)
639 .field("input", &self.input)
640 .field("effective_limits", &self.effective_limits)
641 .field("intent_digest", &self.intent_digest)
642 .finish_non_exhaustive()
643 }
644}
645
646impl<'de> Deserialize<'de> for ToolInvocationIntent {
647 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
648 where
649 D: Deserializer<'de>,
650 {
651 #[derive(Deserialize)]
652 #[serde(deny_unknown_fields)]
653 struct Wire {
654 activation: NodeActivation,
655 invocation_id: InvocationId,
656 descriptor: ToolDescriptor,
657 input: ToolInput,
658 effective_limits: ToolExecutionLimits,
659 intent_digest: Digest,
660 }
661
662 let wire = Wire::deserialize(deserializer)?;
663 Self::restore(
664 wire.activation,
665 wire.invocation_id,
666 wire.descriptor,
667 wire.input,
668 wire.effective_limits,
669 wire.intent_digest,
670 )
671 .map_err(de::Error::custom)
672 }
673}
674
675#[derive(Clone, Debug, Eq, Error, PartialEq)]
677#[non_exhaustive]
678pub enum ToolInvocationIntentError {
679 #[error("tool invocation input schema does not match the descriptor")]
681 InputSchemaMismatch,
682 #[error("effective tool invocation limit {limit:?} exceeds the descriptor ceiling")]
684 EffectiveLimitWidened {
685 limit: ToolInvocationLimit,
687 },
688 #[error("tool invocation input is {actual} bytes; effective maximum is {maximum}")]
690 InputLimitExceeded {
691 maximum: ByteCount,
693 actual: ByteCount,
695 },
696 #[error("tool invocation intent integrity calculation failed: {source}")]
698 Integrity {
699 #[source]
701 source: ToolInvocationIntegrityError,
702 },
703 #[error("tool invocation intent digest does not match its fields")]
705 DigestMismatch,
706}
707
708impl From<ToolInvocationIntegrityError> for ToolInvocationIntentError {
709 fn from(source: ToolInvocationIntegrityError) -> Self {
710 Self::Integrity { source }
711 }
712}
713
714#[derive(
716 Clone, Copy, Debug, Deserialize, Eq, Hash, JsonSchema, Ord, PartialEq, PartialOrd, Serialize,
717)]
718#[serde(rename_all = "snake_case")]
719pub enum ToolInvocationStatus {
720 Prepared,
722 Executing,
724 Committed,
726 Failed,
728 Unknown,
730}
731
732#[derive(Clone, Debug, JsonSchema, Serialize)]
734#[serde(tag = "status", rename_all = "snake_case", deny_unknown_fields)]
735pub enum ToolInvocationState {
736 Prepared,
738 Executing {
740 attempt_id: AttemptId,
742 },
743 Committed {
745 result: ToolResult,
747 },
748 Failed {
750 error: ToolError,
752 },
753 Unknown {
755 error: ToolError,
757 },
758}
759
760impl ToolInvocationState {
761 #[must_use]
763 pub const fn status(&self) -> ToolInvocationStatus {
764 match self {
765 Self::Prepared => ToolInvocationStatus::Prepared,
766 Self::Executing { .. } => ToolInvocationStatus::Executing,
767 Self::Committed { .. } => ToolInvocationStatus::Committed,
768 Self::Failed { .. } => ToolInvocationStatus::Failed,
769 Self::Unknown { .. } => ToolInvocationStatus::Unknown,
770 }
771 }
772
773 #[must_use]
775 pub const fn attempt_id(&self) -> Option<AttemptId> {
776 match self {
777 Self::Prepared => None,
778 Self::Executing { attempt_id } => Some(*attempt_id),
779 Self::Committed { result } => Some(result.provenance().attempt_id()),
780 Self::Failed { error } | Self::Unknown { error } => {
781 Some(error.provenance().attempt_id())
782 }
783 }
784 }
785}
786
787impl<'de> Deserialize<'de> for ToolInvocationState {
788 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
789 where
790 D: Deserializer<'de>,
791 {
792 #[derive(Deserialize)]
793 #[serde(tag = "status", rename_all = "snake_case", deny_unknown_fields)]
794 enum Wire {
795 Prepared,
796 Executing { attempt_id: AttemptId },
797 Committed { result: ToolResult },
798 Failed { error: ToolError },
799 Unknown { error: ToolError },
800 }
801
802 Ok(match Wire::deserialize(deserializer)? {
803 Wire::Prepared => Self::Prepared,
804 Wire::Executing { attempt_id } => Self::Executing { attempt_id },
805 Wire::Committed { result } => Self::Committed { result },
806 Wire::Failed { error } => Self::Failed { error },
807 Wire::Unknown { error } => Self::Unknown { error },
808 })
809 }
810}
811
812#[derive(
814 Clone, Copy, Debug, Deserialize, Eq, Hash, JsonSchema, Ord, PartialEq, PartialOrd, Serialize,
815)]
816#[serde(rename_all = "snake_case")]
817pub enum ToolInvocationTransitionKind {
818 StartAttempt,
820 RecordResult,
822 RecordError,
824 ReconcileResult,
826 ReconcileError,
828}
829
830#[derive(Clone, Debug, Deserialize, JsonSchema, Serialize)]
832#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
833pub enum ToolInvocationTransition {
834 StartAttempt {
836 attempt_id: AttemptId,
838 },
839 RecordResult {
841 result: ToolResult,
843 },
844 RecordError {
846 error: ToolError,
848 },
849 ReconcileResult {
851 result: ToolResult,
853 },
854 ReconcileError {
856 error: ToolError,
858 },
859}
860
861impl ToolInvocationTransition {
862 #[must_use]
864 pub const fn kind(&self) -> ToolInvocationTransitionKind {
865 match self {
866 Self::StartAttempt { .. } => ToolInvocationTransitionKind::StartAttempt,
867 Self::RecordResult { .. } => ToolInvocationTransitionKind::RecordResult,
868 Self::RecordError { .. } => ToolInvocationTransitionKind::RecordError,
869 Self::ReconcileResult { .. } => ToolInvocationTransitionKind::ReconcileResult,
870 Self::ReconcileError { .. } => ToolInvocationTransitionKind::ReconcileError,
871 }
872 }
873}
874
875#[derive(Clone, Debug, Eq, JsonSchema, PartialEq, Serialize)]
881#[serde(deny_unknown_fields)]
882pub struct ToolInvocationHead {
883 tenant_id: TenantId,
884 run_id: RunId,
885 invocation_id: InvocationId,
886 revision: ToolInvocationRevision,
887 status: ToolInvocationStatus,
888 #[serde(skip_serializing_if = "Option::is_none")]
889 attempt_id: Option<AttemptId>,
890 journal_head: JournalHead,
891 digest: Digest,
892}
893
894impl ToolInvocationHead {
895 #[allow(clippy::too_many_arguments)]
902 pub fn new(
903 tenant_id: TenantId,
904 run_id: RunId,
905 invocation_id: InvocationId,
906 revision: ToolInvocationRevision,
907 status: ToolInvocationStatus,
908 attempt_id: Option<AttemptId>,
909 journal_head: JournalHead,
910 digest: Digest,
911 ) -> Result<Self, ToolInvocationHeadError> {
912 validate_journal_scope(&tenant_id, run_id, &journal_head)
913 .map_err(ToolInvocationHeadError::from_scope)?;
914 validate_status_attempt(status, attempt_id)?;
915 validate_revision_status(revision, status)?;
916 Ok(Self {
917 tenant_id,
918 run_id,
919 invocation_id,
920 revision,
921 status,
922 attempt_id,
923 journal_head,
924 digest,
925 })
926 }
927
928 #[must_use]
930 pub const fn tenant_id(&self) -> &TenantId {
931 &self.tenant_id
932 }
933
934 #[must_use]
936 pub const fn run_id(&self) -> RunId {
937 self.run_id
938 }
939
940 #[must_use]
942 pub const fn invocation_id(&self) -> InvocationId {
943 self.invocation_id
944 }
945
946 #[must_use]
948 pub const fn revision(&self) -> ToolInvocationRevision {
949 self.revision
950 }
951
952 #[must_use]
954 pub const fn status(&self) -> ToolInvocationStatus {
955 self.status
956 }
957
958 #[must_use]
960 pub const fn attempt_id(&self) -> Option<AttemptId> {
961 self.attempt_id
962 }
963
964 #[must_use]
966 pub const fn journal_head(&self) -> &JournalHead {
967 &self.journal_head
968 }
969
970 #[must_use]
972 pub const fn digest(&self) -> Digest {
973 self.digest
974 }
975}
976
977impl<'de> Deserialize<'de> for ToolInvocationHead {
978 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
979 where
980 D: Deserializer<'de>,
981 {
982 #[derive(Deserialize)]
983 #[serde(deny_unknown_fields)]
984 struct Wire {
985 tenant_id: TenantId,
986 run_id: RunId,
987 invocation_id: InvocationId,
988 revision: ToolInvocationRevision,
989 status: ToolInvocationStatus,
990 attempt_id: Option<AttemptId>,
991 journal_head: JournalHead,
992 digest: Digest,
993 }
994
995 let wire = Wire::deserialize(deserializer)?;
996 Self::new(
997 wire.tenant_id,
998 wire.run_id,
999 wire.invocation_id,
1000 wire.revision,
1001 wire.status,
1002 wire.attempt_id,
1003 wire.journal_head,
1004 wire.digest,
1005 )
1006 .map_err(de::Error::custom)
1007 }
1008}
1009
1010#[derive(Clone, Debug, Eq, Error, PartialEq)]
1012#[non_exhaustive]
1013pub enum ToolInvocationHeadError {
1014 #[error("tool invocation journal head crosses the tenant boundary")]
1016 JournalTenantMismatch,
1017 #[error("tool invocation journal head does not belong to the run")]
1019 JournalRunMismatch,
1020 #[error("prepared tool invocation head must not contain an attempt")]
1022 PreparedHasAttempt,
1023 #[error("non-prepared tool invocation head must contain an attempt")]
1025 AttemptMissing,
1026 #[error("tool invocation head revision zero must be prepared")]
1028 InitialStatusMismatch,
1029 #[error("prepared tool invocation head must use revision zero")]
1031 PreparedRevisionMismatch,
1032}
1033
1034impl ToolInvocationHeadError {
1035 const fn from_scope(error: InvocationScopeError) -> Self {
1036 match error {
1037 InvocationScopeError::Tenant => Self::JournalTenantMismatch,
1038 InvocationScopeError::Run => Self::JournalRunMismatch,
1039 }
1040 }
1041}
1042
1043#[derive(Clone, JsonSchema, Serialize)]
1050#[serde(deny_unknown_fields)]
1051pub struct ToolInvocation {
1052 intent: ToolInvocationIntent,
1053 revision: ToolInvocationRevision,
1054 state: ToolInvocationState,
1055 #[serde(skip_serializing_if = "Option::is_none")]
1056 previous: Option<ToolInvocationHead>,
1057 journal_head: JournalHead,
1058 #[serde(skip_serializing_if = "Option::is_none")]
1059 transition: Option<ToolInvocationTransition>,
1060 #[serde(skip_serializing_if = "Option::is_none")]
1061 transition_digest: Option<Digest>,
1062 digest: Digest,
1063}
1064
1065impl ToolInvocation {
1066 pub fn prepare(
1076 intent: ToolInvocationIntent,
1077 journal_head: JournalHead,
1078 ) -> Result<Self, ToolInvocationError> {
1079 validate_preparation_journal(&intent, &journal_head)?;
1080 let revision = ToolInvocationRevision::INITIAL;
1081 let state = ToolInvocationState::Prepared;
1082 let digest = compute_record_digest(&ToolInvocationRecordDigestWire {
1083 intent_digest: intent.intent_digest,
1084 revision,
1085 state: &state,
1086 previous: None,
1087 journal_head: &journal_head,
1088 transition_digest: None,
1089 })?;
1090 Ok(Self {
1091 intent,
1092 revision,
1093 state,
1094 previous: None,
1095 journal_head,
1096 transition: None,
1097 transition_digest: None,
1098 digest,
1099 })
1100 }
1101
1102 pub fn advance(
1113 &self,
1114 transition: ToolInvocationTransition,
1115 journal_head: JournalHead,
1116 ) -> Result<Self, ToolInvocationError> {
1117 validate_successor_journal(self, &journal_head)?;
1118 let revision = self
1119 .revision
1120 .checked_next()
1121 .ok_or(ToolInvocationError::RevisionOverflow)?;
1122 let state = apply_transition(self, &transition, journal_head.recorded_at())?;
1123 let transition_digest = compute_transition_digest(&transition)?;
1124 let previous = self.head();
1125 let digest = compute_record_digest(&ToolInvocationRecordDigestWire {
1126 intent_digest: self.intent.intent_digest,
1127 revision,
1128 state: &state,
1129 previous: Some(&previous),
1130 journal_head: &journal_head,
1131 transition_digest: Some(transition_digest),
1132 })?;
1133 Ok(Self {
1134 intent: self.intent.clone(),
1135 revision,
1136 state,
1137 previous: Some(previous),
1138 journal_head,
1139 transition: Some(transition),
1140 transition_digest: Some(transition_digest),
1141 digest,
1142 })
1143 }
1144
1145 #[allow(clippy::too_many_arguments)]
1156 pub fn restore(
1157 intent: ToolInvocationIntent,
1158 revision: ToolInvocationRevision,
1159 state: ToolInvocationState,
1160 previous: Option<ToolInvocationHead>,
1161 journal_head: JournalHead,
1162 transition: Option<ToolInvocationTransition>,
1163 transition_digest: Option<Digest>,
1164 digest: Digest,
1165 ) -> Result<Self, ToolInvocationError> {
1166 validate_record_shape(
1167 &intent,
1168 revision,
1169 &state,
1170 previous.as_ref(),
1171 &journal_head,
1172 transition.as_ref(),
1173 transition_digest,
1174 )?;
1175 let expected = compute_record_digest(&ToolInvocationRecordDigestWire {
1176 intent_digest: intent.intent_digest,
1177 revision,
1178 state: &state,
1179 previous: previous.as_ref(),
1180 journal_head: &journal_head,
1181 transition_digest,
1182 })?;
1183 if digest != expected {
1184 return Err(ToolInvocationError::DigestMismatch);
1185 }
1186 Ok(Self {
1187 intent,
1188 revision,
1189 state,
1190 previous,
1191 journal_head,
1192 transition,
1193 transition_digest,
1194 digest,
1195 })
1196 }
1197
1198 #[must_use]
1200 pub const fn intent(&self) -> &ToolInvocationIntent {
1201 &self.intent
1202 }
1203
1204 #[must_use]
1206 pub const fn revision(&self) -> ToolInvocationRevision {
1207 self.revision
1208 }
1209
1210 #[must_use]
1212 pub const fn state(&self) -> &ToolInvocationState {
1213 &self.state
1214 }
1215
1216 #[must_use]
1218 pub const fn status(&self) -> ToolInvocationStatus {
1219 self.state.status()
1220 }
1221
1222 #[must_use]
1224 pub const fn attempt_id(&self) -> Option<AttemptId> {
1225 self.state.attempt_id()
1226 }
1227
1228 pub fn validate_reconciliation_result(
1239 &self,
1240 result: &ToolResult,
1241 ) -> Result<(), ToolInvocationError> {
1242 let ToolInvocationState::Unknown { error } = &self.state else {
1243 return Err(ToolInvocationError::InvalidTransition {
1244 status: self.status(),
1245 transition: ToolInvocationTransitionKind::ReconcileResult,
1246 });
1247 };
1248 validate_result_binding(&self.intent, error.provenance().attempt_id(), result)
1249 }
1250
1251 pub fn validate_reconciliation_error(
1263 &self,
1264 error: &ToolError,
1265 ) -> Result<(), ToolInvocationError> {
1266 let ToolInvocationState::Unknown { error: previous } = &self.state else {
1267 return Err(ToolInvocationError::InvalidTransition {
1268 status: self.status(),
1269 transition: ToolInvocationTransitionKind::ReconcileError,
1270 });
1271 };
1272 validate_error_binding(&self.intent, previous.provenance().attempt_id(), error)
1273 }
1274
1275 #[must_use]
1277 pub const fn previous(&self) -> Option<&ToolInvocationHead> {
1278 self.previous.as_ref()
1279 }
1280
1281 #[must_use]
1283 pub const fn journal_head(&self) -> &JournalHead {
1284 &self.journal_head
1285 }
1286
1287 #[must_use]
1289 pub const fn transition(&self) -> Option<&ToolInvocationTransition> {
1290 self.transition.as_ref()
1291 }
1292
1293 #[must_use]
1295 pub const fn transition_digest(&self) -> Option<Digest> {
1296 self.transition_digest
1297 }
1298
1299 #[must_use]
1301 pub const fn digest(&self) -> Digest {
1302 self.digest
1303 }
1304
1305 #[must_use]
1307 pub fn head(&self) -> ToolInvocationHead {
1308 ToolInvocationHead {
1309 tenant_id: self.intent.tenant_id().clone(),
1310 run_id: self.intent.run_id(),
1311 invocation_id: self.intent.invocation_id,
1312 revision: self.revision,
1313 status: self.status(),
1314 attempt_id: self.attempt_id(),
1315 journal_head: self.journal_head.clone(),
1316 digest: self.digest,
1317 }
1318 }
1319}
1320
1321impl fmt::Debug for ToolInvocation {
1322 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1323 formatter
1324 .debug_struct("ToolInvocation")
1325 .field("intent", &self.intent)
1326 .field("revision", &self.revision)
1327 .field("state", &self.state)
1328 .field("previous", &self.previous)
1329 .field("journal_head", &self.journal_head)
1330 .field("transition", &self.transition)
1331 .field("transition_digest", &self.transition_digest)
1332 .field("digest", &self.digest)
1333 .finish_non_exhaustive()
1334 }
1335}
1336
1337impl<'de> Deserialize<'de> for ToolInvocation {
1338 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1339 where
1340 D: Deserializer<'de>,
1341 {
1342 #[derive(Deserialize)]
1343 #[serde(deny_unknown_fields)]
1344 struct Wire {
1345 intent: ToolInvocationIntent,
1346 revision: ToolInvocationRevision,
1347 state: ToolInvocationState,
1348 previous: Option<ToolInvocationHead>,
1349 journal_head: JournalHead,
1350 transition: Option<ToolInvocationTransition>,
1351 transition_digest: Option<Digest>,
1352 digest: Digest,
1353 }
1354
1355 let wire = Wire::deserialize(deserializer)?;
1356 Self::restore(
1357 wire.intent,
1358 wire.revision,
1359 wire.state,
1360 wire.previous,
1361 wire.journal_head,
1362 wire.transition,
1363 wire.transition_digest,
1364 wire.digest,
1365 )
1366 .map_err(de::Error::custom)
1367 }
1368}
1369
1370#[derive(Clone, Debug, Default)]
1376pub struct ToolInvocationHistoryVerifier {
1377 last: Option<ToolInvocation>,
1378}
1379
1380impl ToolInvocationHistoryVerifier {
1381 #[must_use]
1383 pub const fn new() -> Self {
1384 Self { last: None }
1385 }
1386
1387 #[must_use]
1393 pub fn after(record: ToolInvocation) -> Self {
1394 Self { last: Some(record) }
1395 }
1396
1397 #[must_use]
1399 pub fn head(&self) -> Option<ToolInvocationHead> {
1400 self.last.as_ref().map(ToolInvocation::head)
1401 }
1402
1403 #[must_use]
1405 pub const fn has_records(&self) -> bool {
1406 self.last.is_some()
1407 }
1408
1409 pub fn verify_next(
1417 &mut self,
1418 record: &ToolInvocation,
1419 ) -> Result<(), ToolInvocationHistoryError> {
1420 let Some(previous) = self.last.as_ref() else {
1421 if record.revision != ToolInvocationRevision::INITIAL {
1422 return Err(ToolInvocationHistoryError::FirstRecordNotInitial {
1423 actual: record.revision,
1424 });
1425 }
1426 self.last = Some(record.clone());
1427 return Ok(());
1428 };
1429
1430 if record.intent != previous.intent {
1431 return Err(ToolInvocationHistoryError::IntentMismatch);
1432 }
1433 if record.previous.as_ref() != Some(&previous.head()) {
1434 return Err(ToolInvocationHistoryError::PreviousHeadMismatch);
1435 }
1436 let transition = record
1437 .transition
1438 .as_ref()
1439 .ok_or(ToolInvocationHistoryError::TransitionMissing)?;
1440 let expected = previous
1441 .advance(transition.clone(), record.journal_head.clone())
1442 .map_err(|source| ToolInvocationHistoryError::Transition { source })?;
1443 if !canonical_equal(&expected, record)
1444 .map_err(|source| ToolInvocationHistoryError::Integrity { source })?
1445 {
1446 return Err(ToolInvocationHistoryError::RecordMismatch);
1447 }
1448
1449 self.last = Some(record.clone());
1450 Ok(())
1451 }
1452}
1453
1454#[derive(Clone, Debug, Eq, Error, PartialEq)]
1456#[non_exhaustive]
1457pub enum ToolInvocationHistoryError {
1458 #[error("first tool invocation record is revision {actual}; expected 0")]
1460 FirstRecordNotInitial {
1461 actual: ToolInvocationRevision,
1463 },
1464 #[error("tool invocation history changed its immutable intent")]
1466 IntentMismatch,
1467 #[error("tool invocation history predecessor head mismatch")]
1469 PreviousHeadMismatch,
1470 #[error("tool invocation history successor is missing its transition")]
1472 TransitionMissing,
1473 #[error("tool invocation history transition is invalid: {source}")]
1475 Transition {
1476 #[source]
1478 source: ToolInvocationError,
1479 },
1480 #[error("tool invocation history successor does not match the applied transition")]
1482 RecordMismatch,
1483 #[error("tool invocation history integrity comparison failed: {source}")]
1485 Integrity {
1486 #[source]
1488 source: ToolInvocationIntegrityError,
1489 },
1490}
1491
1492#[derive(Clone, Copy, Debug, Eq, Hash, JsonSchema, PartialEq)]
1494#[non_exhaustive]
1495pub enum ToolArtifactBinding {
1496 Tenant,
1498 Run,
1500 Principal,
1502 Capability,
1504}
1505
1506#[derive(Clone, Debug, Eq, Error, PartialEq)]
1508#[non_exhaustive]
1509pub enum ToolInvocationError {
1510 #[error("tool invocation integrity calculation failed: {source}")]
1512 Integrity {
1513 #[source]
1515 source: ToolInvocationIntegrityError,
1516 },
1517 #[error("tool invocation journal head crosses the tenant boundary")]
1519 JournalTenantMismatch,
1520 #[error("tool invocation journal head does not belong to the run")]
1522 JournalRunMismatch,
1523 #[error("tool invocation journal sequence {actual} does not advance {previous}")]
1525 JournalDidNotAdvance {
1526 previous: JournalSequence,
1528 actual: JournalSequence,
1530 },
1531 #[error("tool invocation journal clock regressed from {previous} to {actual}")]
1533 ClockRegression {
1534 previous: Timestamp,
1536 actual: Timestamp,
1538 },
1539 #[error("tool invocation revision exceeds the PostgreSQL BIGINT maximum")]
1541 RevisionOverflow,
1542 #[error("initial tool invocation revision must be prepared with no predecessor or transition")]
1544 InvalidInitialShape,
1545 #[error(
1547 "tool invocation successor must contain predecessor, transition, and transition digest"
1548 )]
1549 InvalidSuccessorShape,
1550 #[error("tool invocation predecessor crosses the tenant boundary")]
1552 PreviousTenantMismatch,
1553 #[error("tool invocation predecessor names another run")]
1555 PreviousRunMismatch,
1556 #[error("tool invocation predecessor names another invocation")]
1558 PreviousInvocationMismatch,
1559 #[error("tool invocation revision {actual} does not follow predecessor {previous}")]
1561 PreviousRevisionMismatch {
1562 previous: ToolInvocationRevision,
1564 actual: ToolInvocationRevision,
1566 },
1567 #[error("tool invocation transition digest does not match its payload")]
1569 TransitionDigestMismatch,
1570 #[error("tool invocation transition {transition:?} is invalid from {status:?}")]
1572 InvalidTransition {
1573 status: ToolInvocationStatus,
1575 transition: ToolInvocationTransitionKind,
1577 },
1578 #[error("tool invocation transition payload does not match its resulting state")]
1580 TransitionStateMismatch,
1581 #[error("tool invocation retry must use a new physical attempt identifier")]
1583 ReusedAttemptId,
1584 #[error("tool invocation failure does not authorize retry")]
1586 RetryNotAuthorized,
1587 #[error("tool invocation retry delay exceeds the supported timestamp range")]
1589 RetryDelayOutOfRange,
1590 #[error("tool invocation retry at {actual} precedes not-before time {not_before}")]
1592 RetryDelayNotElapsed {
1593 not_before: Timestamp,
1595 actual: Timestamp,
1597 },
1598 #[error("tool invocation failure evidence does not permit a repeated external call")]
1600 RetryUnsafe,
1601 #[error("tool result names another logical invocation")]
1603 ResultInvocationMismatch,
1604 #[error("tool result names another physical attempt")]
1606 ResultAttemptMismatch,
1607 #[error("tool result names another tool identity")]
1609 ResultToolMismatch,
1610 #[error("tool result names another output schema")]
1612 ResultSchemaMismatch,
1613 #[error("tool result is {actual} inline bytes; effective maximum is {maximum}")]
1615 ResultInlineLimitExceeded {
1616 maximum: ByteCount,
1618 actual: ByteCount,
1620 },
1621 #[error("tool result has {actual} artifacts; effective maximum is {maximum}")]
1623 ResultArtifactCountExceeded {
1624 maximum: ExecutionCount,
1626 actual: ExecutionCount,
1628 },
1629 #[error("tool result artifacts total {actual} bytes; effective maximum is {maximum}")]
1631 ResultArtifactBytesExceeded {
1632 maximum: ByteCount,
1634 actual: ByteCount,
1636 },
1637 #[error("tool result artifact at index {index} has invalid {binding:?} binding")]
1639 ResultArtifactBinding {
1640 index: usize,
1642 binding: ToolArtifactBinding,
1644 },
1645 #[error("tool error names another logical invocation")]
1647 ErrorInvocationMismatch,
1648 #[error("tool error names another physical attempt")]
1650 ErrorAttemptMismatch,
1651 #[error("tool error names another tool identity")]
1653 ErrorToolMismatch,
1654 #[error("tool error effect {effect:?} contradicts descriptor risk {risk:?}")]
1656 ErrorEffectRiskMismatch {
1657 risk: ToolRisk,
1659 effect: ToolExternalEffect,
1661 },
1662 #[error("applied non-idempotent tool write cannot authorize automatic retry")]
1664 UnsafeRetryAfterAppliedNonIdempotentWrite,
1665 #[error("failed tool invocation state cannot contain unknown effect evidence")]
1667 FailedStateHasUnknownEffect,
1668 #[error("unknown tool invocation state requires unknown effect evidence")]
1670 UnknownStateRequiresUnknownEffect,
1671 #[error("tool invocation record digest does not match its fields")]
1673 DigestMismatch,
1674}
1675
1676impl From<ToolInvocationIntegrityError> for ToolInvocationError {
1677 fn from(source: ToolInvocationIntegrityError) -> Self {
1678 Self::Integrity { source }
1679 }
1680}
1681
1682#[derive(Clone, Debug, Eq, Error, PartialEq)]
1684#[non_exhaustive]
1685pub enum ToolInvocationIntegrityError {
1686 #[error("tool invocation checksum preimage canonical serialization failed")]
1688 CanonicalSerialization,
1689}
1690
1691#[derive(Serialize)]
1692struct ReadyNodeInputDigestWire<'a> {
1693 base_checkpoint_digest: Digest,
1694 graph_namespace: &'a GraphNamespace,
1695 node_id: &'a NodeId,
1696}
1697
1698#[derive(Serialize)]
1699struct ToolInvocationIntentDigestWire<'a> {
1700 activation: &'a NodeActivation,
1701 invocation_id: InvocationId,
1702 descriptor: &'a ToolDescriptor,
1703 input: &'a ToolInput,
1704 effective_limits: &'a ToolExecutionLimits,
1705}
1706
1707#[derive(Serialize)]
1708struct ToolInvocationRecordDigestWire<'a> {
1709 intent_digest: Digest,
1710 revision: ToolInvocationRevision,
1711 state: &'a ToolInvocationState,
1712 #[serde(skip_serializing_if = "Option::is_none")]
1713 previous: Option<&'a ToolInvocationHead>,
1714 journal_head: &'a JournalHead,
1715 #[serde(skip_serializing_if = "Option::is_none")]
1716 transition_digest: Option<Digest>,
1717}
1718
1719fn compute_ready_node_input_digest(
1720 base_checkpoint_digest: Digest,
1721 graph_namespace: &GraphNamespace,
1722 node_id: &NodeId,
1723) -> Result<Digest, NodeActivationError> {
1724 let canonical = serde_json_canonicalizer::to_vec(&ReadyNodeInputDigestWire {
1725 base_checkpoint_digest,
1726 graph_namespace,
1727 node_id,
1728 })
1729 .map_err(|_| NodeActivationError::CanonicalSerialization)?;
1730 let mut preimage = Vec::with_capacity(READY_NODE_INPUT_DIGEST_DOMAIN.len() + canonical.len());
1731 preimage.extend_from_slice(READY_NODE_INPUT_DIGEST_DOMAIN);
1732 preimage.extend_from_slice(&canonical);
1733 Ok(Digest::sha256(preimage))
1734}
1735
1736fn compute_intent_digest(
1737 value: &ToolInvocationIntentDigestWire<'_>,
1738) -> Result<Digest, ToolInvocationIntegrityError> {
1739 domain_separated_digest(INTENT_DIGEST_DOMAIN, value)
1740}
1741
1742fn compute_transition_digest(
1743 value: &ToolInvocationTransition,
1744) -> Result<Digest, ToolInvocationIntegrityError> {
1745 domain_separated_digest(TRANSITION_DIGEST_DOMAIN, value)
1746}
1747
1748fn compute_record_digest(
1749 value: &ToolInvocationRecordDigestWire<'_>,
1750) -> Result<Digest, ToolInvocationIntegrityError> {
1751 domain_separated_digest(RECORD_DIGEST_DOMAIN, value)
1752}
1753
1754fn domain_separated_digest<T: Serialize>(
1755 domain: &[u8],
1756 value: &T,
1757) -> Result<Digest, ToolInvocationIntegrityError> {
1758 let canonical = serde_json_canonicalizer::to_vec(value)
1759 .map_err(|_| ToolInvocationIntegrityError::CanonicalSerialization)?;
1760 let mut preimage = Vec::with_capacity(domain.len() + canonical.len());
1761 preimage.extend_from_slice(domain);
1762 preimage.extend_from_slice(&canonical);
1763 Ok(Digest::sha256(preimage))
1764}
1765
1766fn canonical_equal<T: Serialize>(
1767 left: &T,
1768 right: &T,
1769) -> Result<bool, ToolInvocationIntegrityError> {
1770 let left = serde_json_canonicalizer::to_vec(left)
1771 .map_err(|_| ToolInvocationIntegrityError::CanonicalSerialization)?;
1772 let right = serde_json_canonicalizer::to_vec(right)
1773 .map_err(|_| ToolInvocationIntegrityError::CanonicalSerialization)?;
1774 Ok(left == right)
1775}
1776
1777fn validate_intent_shape(
1778 descriptor: &ToolDescriptor,
1779 input: &ToolInput,
1780 effective: &ToolExecutionLimits,
1781) -> Result<(), ToolInvocationIntentError> {
1782 if input.schema() != descriptor.input_schema() {
1783 return Err(ToolInvocationIntentError::InputSchemaMismatch);
1784 }
1785 let descriptor_limits = descriptor.limits();
1786 for (widened, limit) in [
1787 (
1788 effective.timeout() > descriptor_limits.timeout(),
1789 ToolInvocationLimit::Timeout,
1790 ),
1791 (
1792 effective.max_concurrency() > descriptor_limits.max_concurrency(),
1793 ToolInvocationLimit::MaxConcurrency,
1794 ),
1795 (
1796 effective.max_input_bytes() > descriptor_limits.max_input_bytes(),
1797 ToolInvocationLimit::MaxInputBytes,
1798 ),
1799 (
1800 effective.max_inline_result_bytes() > descriptor_limits.max_inline_result_bytes(),
1801 ToolInvocationLimit::MaxInlineResultBytes,
1802 ),
1803 (
1804 effective.max_artifacts() > descriptor_limits.max_artifacts(),
1805 ToolInvocationLimit::MaxArtifacts,
1806 ),
1807 (
1808 effective.max_total_artifact_bytes() > descriptor_limits.max_total_artifact_bytes(),
1809 ToolInvocationLimit::MaxTotalArtifactBytes,
1810 ),
1811 ] {
1812 if widened {
1813 return Err(ToolInvocationIntentError::EffectiveLimitWidened { limit });
1814 }
1815 }
1816
1817 let actual = byte_count_from_usize(input.value().stats().compact_bytes());
1818 let maximum = effective.max_input_bytes();
1819 if actual > maximum {
1820 return Err(ToolInvocationIntentError::InputLimitExceeded { maximum, actual });
1821 }
1822 Ok(())
1823}
1824
1825fn byte_count_from_usize(value: usize) -> ByteCount {
1826 ByteCount::new(u64::try_from(value).unwrap_or(u64::MAX))
1827}
1828
1829fn execution_count_from_usize(value: usize) -> ExecutionCount {
1830 ExecutionCount::new(u64::try_from(value).unwrap_or(u64::MAX))
1831}
1832
1833#[derive(Clone, Copy)]
1834enum InvocationScopeError {
1835 Tenant,
1836 Run,
1837}
1838
1839fn validate_journal_scope(
1840 tenant_id: &TenantId,
1841 run_id: RunId,
1842 head: &JournalHead,
1843) -> Result<(), InvocationScopeError> {
1844 if head.tenant_id() != tenant_id {
1845 return Err(InvocationScopeError::Tenant);
1846 }
1847 if head.run_id() != run_id {
1848 return Err(InvocationScopeError::Run);
1849 }
1850 Ok(())
1851}
1852
1853fn validate_status_attempt(
1854 status: ToolInvocationStatus,
1855 attempt_id: Option<AttemptId>,
1856) -> Result<(), ToolInvocationHeadError> {
1857 match (status, attempt_id) {
1858 (ToolInvocationStatus::Prepared, None)
1859 | (
1860 ToolInvocationStatus::Executing
1861 | ToolInvocationStatus::Committed
1862 | ToolInvocationStatus::Failed
1863 | ToolInvocationStatus::Unknown,
1864 Some(_),
1865 ) => Ok(()),
1866 (ToolInvocationStatus::Prepared, Some(_)) => {
1867 Err(ToolInvocationHeadError::PreparedHasAttempt)
1868 }
1869 (
1870 ToolInvocationStatus::Executing
1871 | ToolInvocationStatus::Committed
1872 | ToolInvocationStatus::Failed
1873 | ToolInvocationStatus::Unknown,
1874 None,
1875 ) => Err(ToolInvocationHeadError::AttemptMissing),
1876 }
1877}
1878
1879fn validate_revision_status(
1880 revision: ToolInvocationRevision,
1881 status: ToolInvocationStatus,
1882) -> Result<(), ToolInvocationHeadError> {
1883 match (revision == ToolInvocationRevision::INITIAL, status) {
1884 (true, ToolInvocationStatus::Prepared)
1885 | (
1886 false,
1887 ToolInvocationStatus::Executing
1888 | ToolInvocationStatus::Committed
1889 | ToolInvocationStatus::Failed
1890 | ToolInvocationStatus::Unknown,
1891 ) => Ok(()),
1892 (true, _) => Err(ToolInvocationHeadError::InitialStatusMismatch),
1893 (false, ToolInvocationStatus::Prepared) => {
1894 Err(ToolInvocationHeadError::PreparedRevisionMismatch)
1895 }
1896 }
1897}
1898
1899fn map_scope_error(error: InvocationScopeError) -> ToolInvocationError {
1900 match error {
1901 InvocationScopeError::Tenant => ToolInvocationError::JournalTenantMismatch,
1902 InvocationScopeError::Run => ToolInvocationError::JournalRunMismatch,
1903 }
1904}
1905
1906fn validate_journal_advances(
1907 previous: &JournalHead,
1908 actual: &JournalHead,
1909) -> Result<(), ToolInvocationError> {
1910 if actual.sequence() <= previous.sequence() {
1911 return Err(ToolInvocationError::JournalDidNotAdvance {
1912 previous: previous.sequence(),
1913 actual: actual.sequence(),
1914 });
1915 }
1916 if actual.recorded_at() < previous.recorded_at() {
1917 return Err(ToolInvocationError::ClockRegression {
1918 previous: previous.recorded_at(),
1919 actual: actual.recorded_at(),
1920 });
1921 }
1922 Ok(())
1923}
1924
1925fn validate_preparation_journal(
1926 intent: &ToolInvocationIntent,
1927 journal_head: &JournalHead,
1928) -> Result<(), ToolInvocationError> {
1929 validate_journal_scope(intent.tenant_id(), intent.run_id(), journal_head)
1930 .map_err(map_scope_error)?;
1931 validate_journal_advances(
1932 intent.activation.base_checkpoint().journal_head(),
1933 journal_head,
1934 )
1935}
1936
1937fn validate_successor_journal(
1938 invocation: &ToolInvocation,
1939 journal_head: &JournalHead,
1940) -> Result<(), ToolInvocationError> {
1941 validate_journal_scope(
1942 invocation.intent.tenant_id(),
1943 invocation.intent.run_id(),
1944 journal_head,
1945 )
1946 .map_err(map_scope_error)?;
1947 validate_journal_advances(&invocation.journal_head, journal_head)
1948}
1949
1950#[allow(clippy::too_many_arguments)]
1951fn validate_record_shape(
1952 intent: &ToolInvocationIntent,
1953 revision: ToolInvocationRevision,
1954 state: &ToolInvocationState,
1955 previous: Option<&ToolInvocationHead>,
1956 journal_head: &JournalHead,
1957 transition: Option<&ToolInvocationTransition>,
1958 transition_digest: Option<Digest>,
1959) -> Result<(), ToolInvocationError> {
1960 validate_journal_scope(intent.tenant_id(), intent.run_id(), journal_head)
1961 .map_err(map_scope_error)?;
1962 validate_state_binding(intent, state)?;
1963
1964 if revision == ToolInvocationRevision::INITIAL {
1965 if !matches!(state, ToolInvocationState::Prepared)
1966 || previous.is_some()
1967 || transition.is_some()
1968 || transition_digest.is_some()
1969 {
1970 return Err(ToolInvocationError::InvalidInitialShape);
1971 }
1972 return validate_preparation_journal(intent, journal_head);
1973 }
1974
1975 let (Some(previous), Some(transition), Some(transition_digest)) =
1976 (previous, transition, transition_digest)
1977 else {
1978 return Err(ToolInvocationError::InvalidSuccessorShape);
1979 };
1980 if previous.tenant_id() != intent.tenant_id() {
1981 return Err(ToolInvocationError::PreviousTenantMismatch);
1982 }
1983 if previous.run_id() != intent.run_id() {
1984 return Err(ToolInvocationError::PreviousRunMismatch);
1985 }
1986 if previous.invocation_id() != intent.invocation_id() {
1987 return Err(ToolInvocationError::PreviousInvocationMismatch);
1988 }
1989 if previous.revision().checked_next() != Some(revision) {
1990 return Err(ToolInvocationError::PreviousRevisionMismatch {
1991 previous: previous.revision(),
1992 actual: revision,
1993 });
1994 }
1995 validate_journal_advances(previous.journal_head(), journal_head)?;
1996
1997 if compute_transition_digest(transition)? != transition_digest {
1998 return Err(ToolInvocationError::TransitionDigestMismatch);
1999 }
2000 validate_transition_shape(intent, previous, transition, state)
2001}
2002
2003fn validate_state_binding(
2004 intent: &ToolInvocationIntent,
2005 state: &ToolInvocationState,
2006) -> Result<(), ToolInvocationError> {
2007 match state {
2008 ToolInvocationState::Prepared | ToolInvocationState::Executing { .. } => Ok(()),
2009 ToolInvocationState::Committed { result } => {
2010 validate_result_binding(intent, result.provenance().attempt_id(), result)
2011 }
2012 ToolInvocationState::Failed { error } => {
2013 validate_error_binding(intent, error.provenance().attempt_id(), error)?;
2014 if error.external_effect() == ToolExternalEffect::Unknown {
2015 return Err(ToolInvocationError::FailedStateHasUnknownEffect);
2016 }
2017 Ok(())
2018 }
2019 ToolInvocationState::Unknown { error } => {
2020 validate_error_binding(intent, error.provenance().attempt_id(), error)?;
2021 if error.external_effect() != ToolExternalEffect::Unknown {
2022 return Err(ToolInvocationError::UnknownStateRequiresUnknownEffect);
2023 }
2024 Ok(())
2025 }
2026 }
2027}
2028
2029fn validate_result_binding(
2030 intent: &ToolInvocationIntent,
2031 expected_attempt: AttemptId,
2032 result: &ToolResult,
2033) -> Result<(), ToolInvocationError> {
2034 let provenance = result.provenance();
2035 if provenance.invocation_id() != intent.invocation_id() {
2036 return Err(ToolInvocationError::ResultInvocationMismatch);
2037 }
2038 if provenance.attempt_id() != expected_attempt {
2039 return Err(ToolInvocationError::ResultAttemptMismatch);
2040 }
2041 if provenance.tool() != intent.descriptor.metadata().identity() {
2042 return Err(ToolInvocationError::ResultToolMismatch);
2043 }
2044 if result.output_schema() != intent.descriptor.output_schema() {
2045 return Err(ToolInvocationError::ResultSchemaMismatch);
2046 }
2047
2048 let actual = byte_count_from_usize(result.output().stats().compact_bytes());
2049 let maximum = intent.effective_limits.max_inline_result_bytes();
2050 if actual > maximum {
2051 return Err(ToolInvocationError::ResultInlineLimitExceeded { maximum, actual });
2052 }
2053 let actual = execution_count_from_usize(result.artifacts().len());
2054 let maximum = intent.effective_limits.max_artifacts();
2055 if actual > maximum {
2056 return Err(ToolInvocationError::ResultArtifactCountExceeded { maximum, actual });
2057 }
2058 let actual = result.artifacts().total_bytes();
2059 let maximum = intent.effective_limits.max_total_artifact_bytes();
2060 if actual > maximum {
2061 return Err(ToolInvocationError::ResultArtifactBytesExceeded { maximum, actual });
2062 }
2063
2064 let expected_principal = intent.descriptor.metadata().identity().owner();
2065 let expected_capability = intent.descriptor.metadata().identity().capability();
2066 for (index, artifact) in result.artifacts().iter().enumerate() {
2067 let binding = if artifact.identity().tenant_id() != intent.tenant_id() {
2068 Some(ToolArtifactBinding::Tenant)
2069 } else if artifact.provenance().run_id() != intent.run_id() {
2070 Some(ToolArtifactBinding::Run)
2071 } else if artifact.provenance().principal() != expected_principal {
2072 Some(ToolArtifactBinding::Principal)
2073 } else if artifact.provenance().capability() != Some(expected_capability) {
2074 Some(ToolArtifactBinding::Capability)
2075 } else {
2076 None
2077 };
2078 if let Some(binding) = binding {
2079 return Err(ToolInvocationError::ResultArtifactBinding { index, binding });
2080 }
2081 }
2082 Ok(())
2083}
2084
2085fn validate_error_binding(
2086 intent: &ToolInvocationIntent,
2087 expected_attempt: AttemptId,
2088 error: &ToolError,
2089) -> Result<(), ToolInvocationError> {
2090 let provenance = error.provenance();
2091 if provenance.invocation_id() != intent.invocation_id() {
2092 return Err(ToolInvocationError::ErrorInvocationMismatch);
2093 }
2094 if provenance.attempt_id() != expected_attempt {
2095 return Err(ToolInvocationError::ErrorAttemptMismatch);
2096 }
2097 if provenance.tool() != intent.descriptor.metadata().identity() {
2098 return Err(ToolInvocationError::ErrorToolMismatch);
2099 }
2100
2101 let risk = intent.descriptor.semantics().risk();
2102 let effect = error.external_effect();
2103 let valid = match risk {
2104 ToolRisk::ReadOnly => effect == ToolExternalEffect::NotApplicable,
2105 ToolRisk::IdempotentWrite | ToolRisk::NonIdempotentWrite => matches!(
2106 effect,
2107 ToolExternalEffect::NotStarted
2108 | ToolExternalEffect::NotApplied
2109 | ToolExternalEffect::Applied
2110 | ToolExternalEffect::Unknown
2111 ),
2112 };
2113 if !valid {
2114 return Err(ToolInvocationError::ErrorEffectRiskMismatch { risk, effect });
2115 }
2116 if risk == ToolRisk::NonIdempotentWrite
2117 && effect == ToolExternalEffect::Applied
2118 && matches!(
2119 error.failure().retry_advice(),
2120 RetryAdvice::SafeAfter { .. }
2121 )
2122 {
2123 return Err(ToolInvocationError::UnsafeRetryAfterAppliedNonIdempotentWrite);
2124 }
2125 Ok(())
2126}
2127
2128fn validate_transition_shape(
2129 intent: &ToolInvocationIntent,
2130 previous: &ToolInvocationHead,
2131 transition: &ToolInvocationTransition,
2132 state: &ToolInvocationState,
2133) -> Result<(), ToolInvocationError> {
2134 let valid = match (previous.status(), transition, state) {
2135 (
2136 ToolInvocationStatus::Prepared | ToolInvocationStatus::Failed,
2137 ToolInvocationTransition::StartAttempt { attempt_id },
2138 ToolInvocationState::Executing {
2139 attempt_id: state_attempt,
2140 },
2141 ) => {
2142 if previous.attempt_id() == Some(*attempt_id) {
2143 return Err(ToolInvocationError::ReusedAttemptId);
2144 }
2145 attempt_id == state_attempt
2146 }
2147 (
2148 ToolInvocationStatus::Executing,
2149 ToolInvocationTransition::RecordResult { result },
2150 ToolInvocationState::Committed {
2151 result: state_result,
2152 },
2153 )
2154 | (
2155 ToolInvocationStatus::Unknown,
2156 ToolInvocationTransition::ReconcileResult { result },
2157 ToolInvocationState::Committed {
2158 result: state_result,
2159 },
2160 ) => result == state_result,
2161 (
2162 ToolInvocationStatus::Executing,
2163 ToolInvocationTransition::RecordError { error },
2164 ToolInvocationState::Failed { error: state_error },
2165 ) if error.external_effect() != ToolExternalEffect::Unknown => {
2166 canonical_equal(error, state_error)?
2167 }
2168 (
2169 ToolInvocationStatus::Executing,
2170 ToolInvocationTransition::RecordError { error },
2171 ToolInvocationState::Unknown { error: state_error },
2172 ) if error.external_effect() == ToolExternalEffect::Unknown => {
2173 canonical_equal(error, state_error)?
2174 }
2175 (
2176 ToolInvocationStatus::Unknown,
2177 ToolInvocationTransition::ReconcileError { error },
2178 ToolInvocationState::Unknown { error: state_error },
2179 ) if error.external_effect() == ToolExternalEffect::Unknown => {
2180 canonical_equal(error, state_error)?
2181 }
2182 (
2183 ToolInvocationStatus::Unknown,
2184 ToolInvocationTransition::ReconcileError { error },
2185 ToolInvocationState::Failed { error: state_error },
2186 ) if error.external_effect() != ToolExternalEffect::Unknown => {
2187 canonical_equal(error, state_error)?
2188 }
2189 _ => {
2190 return Err(ToolInvocationError::InvalidTransition {
2191 status: previous.status(),
2192 transition: transition.kind(),
2193 });
2194 }
2195 };
2196 if !valid {
2197 return Err(ToolInvocationError::TransitionStateMismatch);
2198 }
2199
2200 let expected_attempt = previous.attempt_id();
2201 match transition {
2202 ToolInvocationTransition::StartAttempt { .. } => {}
2203 ToolInvocationTransition::RecordResult { result }
2204 | ToolInvocationTransition::ReconcileResult { result } => {
2205 validate_result_binding(
2206 intent,
2207 expected_attempt.ok_or(ToolInvocationError::TransitionStateMismatch)?,
2208 result,
2209 )?;
2210 }
2211 ToolInvocationTransition::RecordError { error }
2212 | ToolInvocationTransition::ReconcileError { error } => {
2213 validate_error_binding(
2214 intent,
2215 expected_attempt.ok_or(ToolInvocationError::TransitionStateMismatch)?,
2216 error,
2217 )?;
2218 }
2219 }
2220 Ok(())
2221}
2222
2223fn apply_transition(
2224 invocation: &ToolInvocation,
2225 transition: &ToolInvocationTransition,
2226 recorded_at: Timestamp,
2227) -> Result<ToolInvocationState, ToolInvocationError> {
2228 match (&invocation.state, transition) {
2229 (ToolInvocationState::Prepared, ToolInvocationTransition::StartAttempt { attempt_id }) => {
2230 Ok(ToolInvocationState::Executing {
2231 attempt_id: *attempt_id,
2232 })
2233 }
2234 (
2235 ToolInvocationState::Failed { error },
2236 ToolInvocationTransition::StartAttempt { attempt_id },
2237 ) => {
2238 let previous_attempt = error.provenance().attempt_id();
2239 if previous_attempt == *attempt_id {
2240 return Err(ToolInvocationError::ReusedAttemptId);
2241 }
2242 validate_retry(invocation, error, recorded_at)?;
2243 Ok(ToolInvocationState::Executing {
2244 attempt_id: *attempt_id,
2245 })
2246 }
2247 (
2248 ToolInvocationState::Executing { attempt_id },
2249 ToolInvocationTransition::RecordResult { result },
2250 ) => {
2251 validate_result_binding(&invocation.intent, *attempt_id, result)?;
2252 Ok(ToolInvocationState::Committed {
2253 result: result.clone(),
2254 })
2255 }
2256 (
2257 ToolInvocationState::Executing { attempt_id },
2258 ToolInvocationTransition::RecordError { error },
2259 ) => {
2260 validate_error_binding(&invocation.intent, *attempt_id, error)?;
2261 Ok(state_from_error(error.clone()))
2262 }
2263 (
2264 ToolInvocationState::Unknown { error: previous },
2265 ToolInvocationTransition::ReconcileResult { result },
2266 ) => {
2267 validate_result_binding(
2268 &invocation.intent,
2269 previous.provenance().attempt_id(),
2270 result,
2271 )?;
2272 Ok(ToolInvocationState::Committed {
2273 result: result.clone(),
2274 })
2275 }
2276 (
2277 ToolInvocationState::Unknown { error: previous },
2278 ToolInvocationTransition::ReconcileError { error },
2279 ) => {
2280 validate_error_binding(
2281 &invocation.intent,
2282 previous.provenance().attempt_id(),
2283 error,
2284 )?;
2285 Ok(state_from_error(error.clone()))
2286 }
2287 _ => Err(ToolInvocationError::InvalidTransition {
2288 status: invocation.status(),
2289 transition: transition.kind(),
2290 }),
2291 }
2292}
2293
2294fn state_from_error(error: ToolError) -> ToolInvocationState {
2295 if error.external_effect() == ToolExternalEffect::Unknown {
2296 ToolInvocationState::Unknown { error }
2297 } else {
2298 ToolInvocationState::Failed { error }
2299 }
2300}
2301
2302fn validate_retry(
2303 invocation: &ToolInvocation,
2304 error: &ToolError,
2305 recorded_at: Timestamp,
2306) -> Result<(), ToolInvocationError> {
2307 let Some(delay) = error.failure().retry_advice().safe_after_delay() else {
2308 return Err(ToolInvocationError::RetryNotAuthorized);
2309 };
2310 let risk = invocation.intent.descriptor.semantics().risk();
2311 let safe = matches!(
2312 (risk, error.external_effect()),
2313 (ToolRisk::ReadOnly, ToolExternalEffect::NotApplicable)
2314 | (
2315 ToolRisk::IdempotentWrite,
2316 ToolExternalEffect::NotStarted
2317 | ToolExternalEffect::NotApplied
2318 | ToolExternalEffect::Applied
2319 )
2320 | (
2321 ToolRisk::NonIdempotentWrite,
2322 ToolExternalEffect::NotStarted | ToolExternalEffect::NotApplied
2323 )
2324 );
2325 if !safe {
2326 return Err(ToolInvocationError::RetryUnsafe);
2327 }
2328
2329 let not_before_micros = i128::from(invocation.journal_head.recorded_at().unix_micros())
2330 + i128::from(delay.as_i64()) * 1_000;
2331 if not_before_micros > i128::from(Timestamp::MAX.unix_micros()) {
2332 return Err(ToolInvocationError::RetryDelayOutOfRange);
2333 }
2334 let not_before = Timestamp::from_unix_micros(
2335 i64::try_from(not_before_micros).map_err(|_| ToolInvocationError::RetryDelayOutOfRange)?,
2336 )
2337 .map_err(|_| ToolInvocationError::RetryDelayOutOfRange)?;
2338 if recorded_at < not_before {
2339 return Err(ToolInvocationError::RetryDelayNotElapsed {
2340 not_before,
2341 actual: recorded_at,
2342 });
2343 }
2344 Ok(())
2345}
2346
2347#[cfg(test)]
2348mod tests {
2349 use schemars::schema_for;
2350 use serde_json::{Value, from_value, json, to_value};
2351
2352 use super::*;
2353 use crate::{
2354 Checkpoint, DurationMillis, EventId, Failure, FailureCategory, FailureCode, FailureId,
2355 FailureMessage, FailureOrigin, ToolErrorPhase, ToolErrorProvenance,
2356 };
2357
2358 fn fixture(path: &[&str], source: &str) -> Value {
2359 let mut value: Value = serde_json::from_str(source).unwrap();
2360 for component in path {
2361 value = match component.parse::<usize>() {
2362 Ok(index) => value[index].clone(),
2363 Err(_) => value[*component].clone(),
2364 };
2365 }
2366 value
2367 }
2368
2369 fn checkpoint() -> Checkpoint {
2370 from_value(fixture(
2371 &["checkpoints", "0"],
2372 include_str!("../tests/fixtures/core-checkpoint-v1.json"),
2373 ))
2374 .unwrap()
2375 }
2376
2377 fn descriptor() -> ToolDescriptor {
2378 from_value(fixture(
2379 &["descriptors", "valid", "0"],
2380 include_str!("../tests/fixtures/core-tool-v1.json"),
2381 ))
2382 .unwrap()
2383 }
2384
2385 fn input() -> ToolInput {
2386 from_value(fixture(
2387 &["inputs", "valid", "0"],
2388 include_str!("../tests/fixtures/core-tool-runtime-v1.json"),
2389 ))
2390 .unwrap()
2391 }
2392
2393 fn result() -> ToolResult {
2394 from_value(fixture(
2395 &["results", "valid", "0"],
2396 include_str!("../tests/fixtures/core-tool-runtime-v1.json"),
2397 ))
2398 .unwrap()
2399 }
2400
2401 fn fixture_error(index: &str) -> ToolError {
2402 from_value(fixture(
2403 &["errors", "valid", index],
2404 include_str!("../tests/fixtures/core-tool-runtime-v1.json"),
2405 ))
2406 .unwrap()
2407 }
2408
2409 fn invocation_id() -> InvocationId {
2410 "01912345-6789-7abc-8def-0123456789ad".parse().unwrap()
2411 }
2412
2413 fn attempt(suffix: &str) -> AttemptId {
2414 format!("01912345-6789-7abc-8def-0123456789{suffix}")
2415 .parse()
2416 .unwrap()
2417 }
2418
2419 fn intent() -> ToolInvocationIntent {
2420 let checkpoint = checkpoint();
2421 let descriptor = descriptor();
2422 ToolInvocationIntent::new(
2423 NodeActivation::new(
2424 checkpoint.head(),
2425 GraphNamespace::root(),
2426 NodeId::new("authorize").unwrap(),
2427 Digest::sha256(b"node-input"),
2428 ),
2429 invocation_id(),
2430 descriptor.clone(),
2431 input(),
2432 descriptor.limits().clone(),
2433 )
2434 .unwrap()
2435 }
2436
2437 fn journal(intent: &ToolInvocationIntent, sequence: u64) -> JournalHead {
2438 let base = intent
2439 .activation()
2440 .base_checkpoint()
2441 .journal_head()
2442 .recorded_at();
2443 let offset = i64::try_from(sequence - 1).unwrap() * 1_000_000;
2444 let event_id: EventId =
2445 format!("01912345-6789-7abc-8def-0123456789{:02x}", 0xc0 + sequence)
2446 .parse()
2447 .unwrap();
2448 JournalHead::new(
2449 intent.tenant_id().clone(),
2450 intent.run_id(),
2451 JournalSequence::new(sequence).unwrap(),
2452 event_id,
2453 Timestamp::from_unix_micros(base.unix_micros() + offset).unwrap(),
2454 Digest::sha256(sequence.to_be_bytes()),
2455 )
2456 }
2457
2458 fn prepared() -> ToolInvocation {
2459 let intent = intent();
2460 let head = journal(&intent, 2);
2461 ToolInvocation::prepare(intent, head).unwrap()
2462 }
2463
2464 fn safe_error(delay_millis: i64) -> ToolError {
2465 let failure = Failure::new(
2466 "01912345-6789-7abc-8def-0123456789b8"
2467 .parse::<FailureId>()
2468 .unwrap(),
2469 FailureCategory::DependencyUnavailable,
2470 FailureCode::new("tool.dependency_unavailable").unwrap(),
2471 FailureOrigin::new("tool.payments").unwrap(),
2472 FailureMessage::new("The payment dependency is temporarily unavailable.").unwrap(),
2473 RetryAdvice::SafeAfter {
2474 delay: DurationMillis::new(delay_millis).unwrap(),
2475 },
2476 )
2477 .unwrap();
2478 ToolError::new(
2479 failure,
2480 ToolErrorPhase::Execution,
2481 ToolExternalEffect::NotApplied,
2482 ToolErrorProvenance::new(
2483 invocation_id(),
2484 attempt("ab"),
2485 descriptor().metadata().identity().clone(),
2486 ),
2487 )
2488 .unwrap()
2489 }
2490
2491 #[test]
2492 fn namespace_and_revision_wires_are_canonical_and_bounded() {
2493 for valid in ["", "parent", "parent/child-v2", "a.b/c_d"] {
2494 let namespace = GraphNamespace::new(valid).unwrap();
2495 assert_eq!(to_value(&namespace).unwrap(), json!(valid));
2496 assert_eq!(
2497 from_value::<GraphNamespace>(json!(valid)).unwrap(),
2498 namespace
2499 );
2500 }
2501 for invalid in ["/node", "node/", "node//child", ".", "parent/.."] {
2502 assert!(GraphNamespace::new(invalid).is_err());
2503 }
2504 assert!(GraphNamespace::new("a".repeat(GraphNamespace::MAX_LEN + 1)).is_err());
2505
2506 for value in [0, 1, MAX_DATABASE_ORDINAL] {
2507 let revision = ToolInvocationRevision::new(value).unwrap();
2508 assert_eq!(
2509 revision
2510 .to_string()
2511 .parse::<ToolInvocationRevision>()
2512 .unwrap(),
2513 revision
2514 );
2515 assert_eq!(
2516 from_value::<ToolInvocationRevision>(json!(value.to_string())).unwrap(),
2517 revision
2518 );
2519 }
2520 for invalid in [
2521 json!(0),
2522 json!("00"),
2523 json!("-1"),
2524 json!("9223372036854775808"),
2525 ] {
2526 assert!(from_value::<ToolInvocationRevision>(invalid).is_err());
2527 }
2528 }
2529
2530 #[test]
2531 fn ready_root_activation_is_deterministic_and_checkpoint_bound() {
2532 let checkpoint = checkpoint();
2533 let node_id = NodeId::new("authorize").unwrap();
2534 let first = NodeActivation::for_ready_root(&checkpoint, node_id.clone()).unwrap();
2535 let replayed = NodeActivation::for_ready_root(&checkpoint, node_id).unwrap();
2536
2537 assert_eq!(first, replayed);
2538 assert_eq!(first.base_checkpoint(), &checkpoint.head());
2539 assert!(first.graph_namespace().is_root());
2540 assert_eq!(first.node_id().as_str(), "authorize");
2541 assert_eq!(
2542 first.input_digest(),
2543 "sha256:fe68cf4a42614bfc0bf4b41ab0fd3e552840e2a389bb61354af2dbdff086bb2c"
2544 .parse()
2545 .unwrap()
2546 );
2547
2548 let sibling =
2549 NodeActivation::for_ready_root(&checkpoint, NodeId::new("reserve-stock").unwrap())
2550 .unwrap();
2551 assert_ne!(first.input_digest(), sibling.input_digest());
2552
2553 assert_eq!(
2554 NodeActivation::for_ready_root(&checkpoint, NodeId::new("not-ready").unwrap(),),
2555 Err(NodeActivationError::NodeNotReady {
2556 node_id: NodeId::new("not-ready").unwrap(),
2557 })
2558 );
2559 }
2560
2561 #[test]
2562 fn intent_is_narrowed_integrity_bound_and_secret_safe_in_debug() {
2563 let intent = intent();
2564 let restored = from_value::<ToolInvocationIntent>(to_value(&intent).unwrap()).unwrap();
2565 assert_eq!(restored, intent);
2566
2567 let mut tampered = to_value(&intent).unwrap();
2568 tampered["input"]["value"]["amount"] = json!(43);
2569 assert!(from_value::<ToolInvocationIntent>(tampered).is_err());
2570
2571 let descriptor = descriptor();
2572 let widened = ToolExecutionLimits::new(
2573 DurationMillis::new(descriptor.limits().timeout().as_i64() + 1).unwrap(),
2574 descriptor.limits().max_concurrency(),
2575 descriptor.limits().max_input_bytes(),
2576 descriptor.limits().max_inline_result_bytes(),
2577 descriptor.limits().max_artifacts(),
2578 descriptor.limits().max_total_artifact_bytes(),
2579 )
2580 .unwrap();
2581 assert_eq!(
2582 ToolInvocationIntent::new(
2583 intent.activation().clone(),
2584 invocation_id(),
2585 descriptor,
2586 input(),
2587 widened,
2588 ),
2589 Err(ToolInvocationIntentError::EffectiveLimitWidened {
2590 limit: ToolInvocationLimit::Timeout,
2591 })
2592 );
2593
2594 let debug = format!("{intent:?}");
2595 assert!(!debug.contains("CNY"));
2596 assert!(!debug.contains("amount"));
2597 assert!(debug.contains("ToolInput"));
2598 }
2599
2600 #[test]
2601 fn success_path_round_trips_and_history_verifies_transactionally() {
2602 let prepared = prepared();
2603 let executing = prepared
2604 .advance(
2605 ToolInvocationTransition::StartAttempt {
2606 attempt_id: attempt("ab"),
2607 },
2608 journal(prepared.intent(), 3),
2609 )
2610 .unwrap();
2611 let committed = executing
2612 .advance(
2613 ToolInvocationTransition::RecordResult { result: result() },
2614 journal(executing.intent(), 4),
2615 )
2616 .unwrap();
2617
2618 assert_eq!(prepared.status(), ToolInvocationStatus::Prepared);
2619 assert_eq!(executing.status(), ToolInvocationStatus::Executing);
2620 assert_eq!(committed.status(), ToolInvocationStatus::Committed);
2621 assert_eq!(committed.revision().get(), 2);
2622 let decoded = from_value::<ToolInvocation>(to_value(&committed).unwrap()).unwrap();
2623 assert_eq!(decoded.head(), committed.head());
2624
2625 let mut verifier = ToolInvocationHistoryVerifier::new();
2626 for record in [&prepared, &executing, &committed] {
2627 verifier.verify_next(record).unwrap();
2628 }
2629 assert_eq!(verifier.head(), Some(committed.head()));
2630
2631 assert!(matches!(
2632 committed.advance(
2633 ToolInvocationTransition::StartAttempt {
2634 attempt_id: attempt("ac"),
2635 },
2636 journal(committed.intent(), 5),
2637 ),
2638 Err(ToolInvocationError::InvalidTransition {
2639 status: ToolInvocationStatus::Committed,
2640 transition: ToolInvocationTransitionKind::StartAttempt,
2641 })
2642 ));
2643 }
2644
2645 #[test]
2646 fn unknown_outcome_cannot_retry_and_only_reconciliation_resolves_it() {
2647 let prepared = prepared();
2648 let executing = prepared
2649 .advance(
2650 ToolInvocationTransition::StartAttempt {
2651 attempt_id: attempt("ab"),
2652 },
2653 journal(prepared.intent(), 3),
2654 )
2655 .unwrap();
2656 let unknown = executing
2657 .advance(
2658 ToolInvocationTransition::RecordError {
2659 error: fixture_error("1"),
2660 },
2661 journal(executing.intent(), 4),
2662 )
2663 .unwrap();
2664 assert_eq!(unknown.status(), ToolInvocationStatus::Unknown);
2665 unknown.validate_reconciliation_result(&result()).unwrap();
2666 unknown
2667 .validate_reconciliation_error(&fixture_error("1"))
2668 .unwrap();
2669 assert!(matches!(
2670 prepared.validate_reconciliation_result(&result()),
2671 Err(ToolInvocationError::InvalidTransition {
2672 status: ToolInvocationStatus::Prepared,
2673 transition: ToolInvocationTransitionKind::ReconcileResult,
2674 })
2675 ));
2676 assert!(matches!(
2677 unknown.advance(
2678 ToolInvocationTransition::StartAttempt {
2679 attempt_id: attempt("ac"),
2680 },
2681 journal(unknown.intent(), 5),
2682 ),
2683 Err(ToolInvocationError::InvalidTransition {
2684 status: ToolInvocationStatus::Unknown,
2685 transition: ToolInvocationTransitionKind::StartAttempt,
2686 })
2687 ));
2688
2689 let reconciled = unknown
2690 .advance(
2691 ToolInvocationTransition::ReconcileResult { result: result() },
2692 journal(unknown.intent(), 5),
2693 )
2694 .unwrap();
2695 assert_eq!(reconciled.status(), ToolInvocationStatus::Committed);
2696 assert!(matches!(
2697 reconciled.validate_reconciliation_error(&fixture_error("1")),
2698 Err(ToolInvocationError::InvalidTransition {
2699 status: ToolInvocationStatus::Committed,
2700 transition: ToolInvocationTransitionKind::ReconcileError,
2701 })
2702 ));
2703 }
2704
2705 #[test]
2706 fn retry_requires_explicit_safety_and_elapsed_delay() {
2707 let prepared = prepared();
2708 let executing = prepared
2709 .advance(
2710 ToolInvocationTransition::StartAttempt {
2711 attempt_id: attempt("ab"),
2712 },
2713 journal(prepared.intent(), 3),
2714 )
2715 .unwrap();
2716 let failed = executing
2717 .advance(
2718 ToolInvocationTransition::RecordError {
2719 error: safe_error(2_000),
2720 },
2721 journal(executing.intent(), 4),
2722 )
2723 .unwrap();
2724
2725 let early_head = JournalHead::new(
2726 failed.intent().tenant_id().clone(),
2727 failed.intent().run_id(),
2728 JournalSequence::new(5).unwrap(),
2729 "01912345-6789-7abc-8def-0123456789c5".parse().unwrap(),
2730 Timestamp::from_unix_micros(
2731 failed.journal_head().recorded_at().unix_micros() + 1_000_000,
2732 )
2733 .unwrap(),
2734 Digest::sha256(b"early"),
2735 );
2736 assert!(matches!(
2737 failed.advance(
2738 ToolInvocationTransition::StartAttempt {
2739 attempt_id: attempt("ac"),
2740 },
2741 early_head,
2742 ),
2743 Err(ToolInvocationError::RetryDelayNotElapsed { .. })
2744 ));
2745
2746 let retried = failed
2747 .advance(
2748 ToolInvocationTransition::StartAttempt {
2749 attempt_id: attempt("ac"),
2750 },
2751 journal(failed.intent(), 6),
2752 )
2753 .unwrap();
2754 assert_eq!(retried.attempt_id(), Some(attempt("ac")));
2755
2756 let never_failed = executing
2757 .advance(
2758 ToolInvocationTransition::RecordError {
2759 error: fixture_error("0"),
2760 },
2761 journal(executing.intent(), 4),
2762 )
2763 .unwrap();
2764 assert!(matches!(
2765 never_failed.advance(
2766 ToolInvocationTransition::StartAttempt {
2767 attempt_id: attempt("ac"),
2768 },
2769 journal(never_failed.intent(), 5),
2770 ),
2771 Err(ToolInvocationError::RetryNotAuthorized)
2772 ));
2773 }
2774
2775 #[test]
2776 fn tampering_and_branch_substitution_fail_closed() {
2777 let prepared = prepared();
2778 let executing = prepared
2779 .advance(
2780 ToolInvocationTransition::StartAttempt {
2781 attempt_id: attempt("ab"),
2782 },
2783 journal(prepared.intent(), 3),
2784 )
2785 .unwrap();
2786 let mut wire = to_value(&executing).unwrap();
2787 wire["state"]["attempt_id"] = json!(attempt("ac"));
2788 assert!(from_value::<ToolInvocation>(wire).is_err());
2789
2790 let mut wire = to_value(&executing).unwrap();
2791 wire["transition_digest"] = json!(Digest::sha256(b"wrong-transition"));
2792 assert!(from_value::<ToolInvocation>(wire).is_err());
2793
2794 let branch = prepared
2795 .advance(
2796 ToolInvocationTransition::StartAttempt {
2797 attempt_id: attempt("ac"),
2798 },
2799 journal(prepared.intent(), 4),
2800 )
2801 .unwrap();
2802 let mut verifier = ToolInvocationHistoryVerifier::new();
2803 verifier.verify_next(&prepared).unwrap();
2804 verifier.verify_next(&executing).unwrap();
2805 let accepted = verifier.head();
2806 assert_eq!(
2807 verifier.verify_next(&branch),
2808 Err(ToolInvocationHistoryError::PreviousHeadMismatch)
2809 );
2810 assert_eq!(verifier.head(), accepted);
2811 }
2812
2813 #[test]
2814 fn public_object_schemas_are_closed() {
2815 for schema in [
2816 to_value(schema_for!(NodeActivation)).unwrap(),
2817 to_value(schema_for!(ToolInvocationIntent)).unwrap(),
2818 to_value(schema_for!(ToolInvocationHead)).unwrap(),
2819 to_value(schema_for!(ToolInvocation)).unwrap(),
2820 ] {
2821 assert_eq!(schema["additionalProperties"], false);
2822 }
2823 }
2824}