Skip to main content

stateknot_core/
node_result.rs

1// Copyright 2026 StateKnot contributors
2// SPDX-License-Identifier: Apache-2.0
3
4//! Immutable pending node results for deterministic graph barriers.
5//!
6//! A successful logical node activation commits exactly one pending result
7//! before a superstep barrier may reduce state. The semantic intent is
8//! independent of the physical worker that won the commit, while the final
9//! record retains that worker's exact run fence and journal anchor. Tool and
10//! model observations are referenced only through committed, activation-bound
11//! ledger revisions; their potentially large payloads are never copied here.
12
13use std::{collections::BTreeSet, fmt, str::FromStr};
14
15use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema};
16use serde::{
17    Deserialize, Deserializer, Serialize, Serializer,
18    de::{self, SeqAccess},
19};
20use thiserror::Error;
21
22use crate::{
23    BoundedJson, CanonicalJson, CanonicalJsonError, Digest, EventId, InterruptId,
24    InterruptRequestIntent, InvocationId, JournalHead, JournalPayload, JsonLimits, ModelInvocation,
25    ModelInvocationHead, ModelInvocationStatus, NodeActivation, PrincipalIdentity, RunFence, RunId,
26    RunInterruptKind, RunTimerKind, SchemaReference, ScopeSet, TenantId, TimerId,
27    TimerRegistrationIntent, ToolInvocation, ToolInvocationHead, ToolInvocationStatus,
28    WaitRegistrationIntent,
29};
30
31const ROUTE_ID_PATTERN: &str = "^(?!\\.{1,2}$)[A-Za-z0-9][A-Za-z0-9_.-]{0,127}$";
32const UPDATE_DIGEST_DOMAIN: &[u8] = b"stateknot-node-state-update-v1\0";
33const TERMINAL_DIGEST_DOMAIN: &[u8] = b"stateknot-node-terminal-output-v1\0";
34const INTENT_DIGEST_DOMAIN: &[u8] = b"stateknot-pending-node-result-intent-v1\0";
35const RECORD_DIGEST_DOMAIN: &[u8] = b"stateknot-pending-node-result-v1\0";
36
37/// Stable conditional route identity declared by a compiled graph.
38///
39/// A route identifies a graph-definition branch, not a destination node. The
40/// barrier resolves it through the exact graph version pinned by the base
41/// checkpoint, which permits one route to fan out without runtime graph
42/// mutation.
43#[derive(Clone, Eq, Hash, Ord, PartialEq, PartialOrd)]
44pub struct RouteId(Box<str>);
45
46impl RouteId {
47    /// Maximum encoded route identity length in bytes.
48    pub const MAX_LEN: usize = 128;
49
50    /// Validates and constructs a route identity.
51    ///
52    /// # Errors
53    ///
54    /// Returns [`RouteIdError`] for an empty, path-like, oversized, or
55    /// non-canonical ASCII identity.
56    pub fn new(value: impl Into<String>) -> Result<Self, RouteIdError> {
57        let value = value.into();
58        validate_route_id(&value)?;
59        Ok(Self(value.into_boxed_str()))
60    }
61
62    /// Returns the exact route identity text.
63    #[must_use]
64    pub fn as_str(&self) -> &str {
65        &self.0
66    }
67}
68
69impl AsRef<str> for RouteId {
70    fn as_ref(&self) -> &str {
71        self.as_str()
72    }
73}
74
75impl fmt::Debug for RouteId {
76    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
77        formatter
78            .debug_tuple("RouteId")
79            .field(&self.as_str())
80            .finish()
81    }
82}
83
84impl fmt::Display for RouteId {
85    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
86        formatter.write_str(self.as_str())
87    }
88}
89
90impl FromStr for RouteId {
91    type Err = RouteIdError;
92
93    fn from_str(value: &str) -> Result<Self, Self::Err> {
94        Self::new(value)
95    }
96}
97
98impl TryFrom<String> for RouteId {
99    type Error = RouteIdError;
100
101    fn try_from(value: String) -> Result<Self, Self::Error> {
102        Self::new(value)
103    }
104}
105
106impl TryFrom<&str> for RouteId {
107    type Error = RouteIdError;
108
109    fn try_from(value: &str) -> Result<Self, Self::Error> {
110        Self::new(value)
111    }
112}
113
114impl Serialize for RouteId {
115    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
116    where
117        S: Serializer,
118    {
119        serializer.serialize_str(self.as_str())
120    }
121}
122
123impl<'de> Deserialize<'de> for RouteId {
124    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
125    where
126        D: Deserializer<'de>,
127    {
128        deserializer.deserialize_str(RouteIdVisitor)
129    }
130}
131
132struct RouteIdVisitor;
133
134impl de::Visitor<'_> for RouteIdVisitor {
135    type Value = RouteId;
136
137    fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
138        formatter.write_str("a bounded canonical graph route identifier")
139    }
140
141    fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
142    where
143        E: de::Error,
144    {
145        RouteId::try_from(value).map_err(E::custom)
146    }
147}
148
149impl JsonSchema for RouteId {
150    fn schema_name() -> std::borrow::Cow<'static, str> {
151        "RouteId".into()
152    }
153
154    fn schema_id() -> std::borrow::Cow<'static, str> {
155        concat!(module_path!(), "::RouteId").into()
156    }
157
158    fn json_schema(_: &mut SchemaGenerator) -> Schema {
159        json_schema!({
160            "type": "string",
161            "minLength": 1,
162            "maxLength": 128,
163            "pattern": ROUTE_ID_PATTERN
164        })
165    }
166
167    fn inline_schema() -> bool {
168        true
169    }
170}
171
172/// Invalid conditional route identity.
173#[derive(Clone, Debug, Eq, Error, PartialEq)]
174#[non_exhaustive]
175pub enum RouteIdError {
176    /// Route identity was empty.
177    #[error("route identifier must not be empty")]
178    Empty,
179    /// Route identity exceeded [`RouteId::MAX_LEN`].
180    #[error("route identifier is {actual} bytes; maximum is {maximum}")]
181    TooLong {
182        /// Maximum accepted bytes.
183        maximum: usize,
184        /// Observed bytes.
185        actual: usize,
186    },
187    /// Route identity was `.` or `..`.
188    #[error("route identifier must not be path-like")]
189    PathLike,
190    /// A byte was outside the stable ASCII grammar.
191    #[error("route identifier contains an invalid byte at offset {index}")]
192    InvalidByte {
193        /// Zero-based byte offset.
194        index: usize,
195    },
196}
197
198fn validate_route_id(value: &str) -> Result<(), RouteIdError> {
199    if value.is_empty() {
200        return Err(RouteIdError::Empty);
201    }
202    if value.len() > RouteId::MAX_LEN {
203        return Err(RouteIdError::TooLong {
204            maximum: RouteId::MAX_LEN,
205            actual: value.len(),
206        });
207    }
208    if matches!(value, "." | "..") {
209        return Err(RouteIdError::PathLike);
210    }
211    for (index, byte) in value.bytes().enumerate() {
212        let valid = if index == 0 {
213            byte.is_ascii_alphanumeric()
214        } else {
215            byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'.' | b'-')
216        };
217        if !valid {
218            return Err(RouteIdError::InvalidByte { index });
219        }
220    }
221    Ok(())
222}
223
224/// Schema-pinned bounded update emitted by one successful node activation.
225///
226/// The graph registry must validate [`Self::data`] against [`Self::schema`]
227/// before construction. This type independently binds the schema identity and
228/// RFC 8785 data bytes so storage corruption cannot substitute either field.
229#[derive(Clone, Eq, JsonSchema, PartialEq, Serialize)]
230#[serde(deny_unknown_fields)]
231pub struct NodeStateUpdate {
232    schema: SchemaReference,
233    data: BoundedJson,
234    digest: Digest,
235}
236
237impl NodeStateUpdate {
238    /// Constructs and checksums a validated update.
239    ///
240    /// # Errors
241    ///
242    /// Returns [`NodeStateUpdateError::Integrity`] when canonicalization fails.
243    pub fn new(schema: SchemaReference, data: BoundedJson) -> Result<Self, NodeStateUpdateError> {
244        let digest = compute_payload_digest(UPDATE_DIGEST_DOMAIN, &schema, &data)
245            .map_err(NodeStateUpdateError::integrity)?;
246        Ok(Self {
247            schema,
248            data,
249            digest,
250        })
251    }
252
253    /// Restores a durable update and verifies its checksum.
254    ///
255    /// # Errors
256    ///
257    /// Returns [`NodeStateUpdateError`] for canonicalization failure or a
258    /// mismatched persisted digest.
259    pub fn restore(
260        schema: SchemaReference,
261        data: BoundedJson,
262        digest: Digest,
263    ) -> Result<Self, NodeStateUpdateError> {
264        let restored = Self::new(schema, data)?;
265        if restored.digest != digest {
266            return Err(NodeStateUpdateError::DigestMismatch);
267        }
268        Ok(restored)
269    }
270
271    /// Returns the pinned update schema.
272    #[must_use]
273    pub const fn schema(&self) -> &SchemaReference {
274        &self.schema
275    }
276
277    /// Returns the bounded update JSON.
278    #[must_use]
279    pub const fn data(&self) -> &BoundedJson {
280        &self.data
281    }
282
283    /// Returns the domain-separated update checksum.
284    #[must_use]
285    pub const fn digest(&self) -> Digest {
286        self.digest
287    }
288}
289
290impl fmt::Debug for NodeStateUpdate {
291    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
292        formatter
293            .debug_struct("NodeStateUpdate")
294            .field("schema", &self.schema)
295            .field("data_stats", &self.data.stats())
296            .field("digest", &self.digest)
297            .finish_non_exhaustive()
298    }
299}
300
301impl<'de> Deserialize<'de> for NodeStateUpdate {
302    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
303    where
304        D: Deserializer<'de>,
305    {
306        #[derive(Deserialize)]
307        #[serde(deny_unknown_fields)]
308        struct Wire {
309            schema: SchemaReference,
310            #[serde(deserialize_with = "deserialize_maximum_json")]
311            data: BoundedJson,
312            digest: Digest,
313        }
314
315        let wire = Wire::deserialize(deserializer)?;
316        Self::restore(wire.schema, wire.data, wire.digest).map_err(de::Error::custom)
317    }
318}
319
320/// Invalid or corrupted schema-pinned node update.
321#[derive(Clone, Debug, Eq, Error, PartialEq)]
322#[non_exhaustive]
323pub enum NodeStateUpdateError {
324    /// Canonical integrity material could not be produced.
325    #[error("node state update integrity calculation failed: {source}")]
326    Integrity {
327        /// Exact integrity failure.
328        #[source]
329        source: PendingNodeResultIntegrityError,
330    },
331    /// The supplied checksum did not match the schema and data.
332    #[error("node state update digest does not match its fields")]
333    DigestMismatch,
334}
335
336impl NodeStateUpdateError {
337    const fn integrity(source: PendingNodeResultIntegrityError) -> Self {
338        Self::Integrity { source }
339    }
340}
341
342/// Schema-pinned bounded output emitted by a terminal graph node.
343#[derive(Clone, Eq, JsonSchema, PartialEq, Serialize)]
344#[serde(deny_unknown_fields)]
345pub struct NodeTerminalOutput {
346    schema: SchemaReference,
347    data: BoundedJson,
348    digest: Digest,
349}
350
351impl NodeTerminalOutput {
352    /// Constructs and checksums validated terminal output.
353    ///
354    /// # Errors
355    ///
356    /// Returns [`NodeTerminalOutputError::Integrity`] when canonicalization
357    /// fails.
358    pub fn new(
359        schema: SchemaReference,
360        data: BoundedJson,
361    ) -> Result<Self, NodeTerminalOutputError> {
362        let digest = compute_payload_digest(TERMINAL_DIGEST_DOMAIN, &schema, &data)
363            .map_err(NodeTerminalOutputError::integrity)?;
364        Ok(Self {
365            schema,
366            data,
367            digest,
368        })
369    }
370
371    /// Restores durable output and verifies its checksum.
372    ///
373    /// # Errors
374    ///
375    /// Returns [`NodeTerminalOutputError`] for canonicalization failure or a
376    /// mismatched persisted digest.
377    pub fn restore(
378        schema: SchemaReference,
379        data: BoundedJson,
380        digest: Digest,
381    ) -> Result<Self, NodeTerminalOutputError> {
382        let restored = Self::new(schema, data)?;
383        if restored.digest != digest {
384            return Err(NodeTerminalOutputError::DigestMismatch);
385        }
386        Ok(restored)
387    }
388
389    /// Returns the graph output schema.
390    #[must_use]
391    pub const fn schema(&self) -> &SchemaReference {
392        &self.schema
393    }
394
395    /// Returns bounded terminal output JSON.
396    #[must_use]
397    pub const fn data(&self) -> &BoundedJson {
398        &self.data
399    }
400
401    /// Returns the domain-separated output checksum.
402    #[must_use]
403    pub const fn digest(&self) -> Digest {
404        self.digest
405    }
406}
407
408impl fmt::Debug for NodeTerminalOutput {
409    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
410        formatter
411            .debug_struct("NodeTerminalOutput")
412            .field("schema", &self.schema)
413            .field("data_stats", &self.data.stats())
414            .field("digest", &self.digest)
415            .finish_non_exhaustive()
416    }
417}
418
419impl<'de> Deserialize<'de> for NodeTerminalOutput {
420    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
421    where
422        D: Deserializer<'de>,
423    {
424        #[derive(Deserialize)]
425        #[serde(deny_unknown_fields)]
426        struct Wire {
427            schema: SchemaReference,
428            #[serde(deserialize_with = "deserialize_maximum_json")]
429            data: BoundedJson,
430            digest: Digest,
431        }
432
433        let wire = Wire::deserialize(deserializer)?;
434        Self::restore(wire.schema, wire.data, wire.digest).map_err(de::Error::custom)
435    }
436}
437
438/// Invalid or corrupted schema-pinned terminal output.
439#[derive(Clone, Debug, Eq, Error, PartialEq)]
440#[non_exhaustive]
441pub enum NodeTerminalOutputError {
442    /// Canonical integrity material could not be produced.
443    #[error("node terminal output integrity calculation failed: {source}")]
444    Integrity {
445        /// Exact integrity failure.
446        #[source]
447        source: PendingNodeResultIntegrityError,
448    },
449    /// The supplied checksum did not match the schema and data.
450    #[error("node terminal output digest does not match its fields")]
451    DigestMismatch,
452}
453
454impl NodeTerminalOutputError {
455    const fn integrity(source: PendingNodeResultIntegrityError) -> Self {
456        Self::Integrity { source }
457    }
458}
459
460fn deserialize_maximum_json<'de, D>(deserializer: D) -> Result<BoundedJson, D::Error>
461where
462    D: Deserializer<'de>,
463{
464    BoundedJson::deserialize_with_limits(deserializer, JsonLimits::MAXIMUM)
465}
466
467/// State contribution from one successful logical node activation.
468#[derive(Clone, Debug, Deserialize, Eq, JsonSchema, PartialEq, Serialize)]
469#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
470pub enum NodeStateChange {
471    /// The activation intentionally emitted no state update.
472    Unchanged,
473    /// The activation emitted one schema-validated typed update.
474    Update {
475        /// Exact update consumed by the compiled reducer plan.
476        update: NodeStateUpdate,
477    },
478}
479
480impl NodeStateChange {
481    /// Returns the update when this activation changed state.
482    #[must_use]
483    pub const fn update(&self) -> Option<&NodeStateUpdate> {
484        match self {
485            Self::Unchanged => None,
486            Self::Update { update } => Some(update),
487        }
488    }
489}
490
491/// Complete, uncommitted lifecycle condition emitted by a graph node.
492///
493/// Unlike [`crate::RunWait`], this value deliberately has no registration
494/// timestamp or journal identity. Those are authoritative database facts that
495/// exist only when the lifecycle coordinator atomically commits the graph
496/// barrier and wait registrations. Every policy-bearing interrupt field is
497/// retained here so recovery can reproduce the exact registration without
498/// consulting mutable application configuration.
499#[derive(Clone, Eq, JsonSchema, PartialEq, Serialize)]
500#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
501#[allow(clippy::large_enum_variant)]
502pub enum NodeWait {
503    /// Require one authenticated, authorized external resolution.
504    Interrupt {
505        /// Stable interrupt identity selected before node-result commit.
506        interrupt_id: InterruptId,
507        /// Protocol-neutral reason the run needs external input.
508        interrupt_kind: RunInterruptKind,
509        /// Complete schema-pinned public request payload.
510        request_payload: JournalPayload,
511        /// Immutable action or question protected by the resolution.
512        action_digest: Digest,
513        /// Exact required resolver, when policy selected one.
514        #[serde(skip_serializing_if = "Option::is_none")]
515        required_principal: Option<PrincipalIdentity>,
516        /// Every scope the resolver must possess.
517        required_scopes: ScopeSet,
518        /// Exclusive resolution expiry, when finite.
519        #[serde(skip_serializing_if = "Option::is_none")]
520        expires_at: Option<crate::Timestamp>,
521    },
522    /// Require one database-clock timer observation.
523    Timer {
524        /// Stable timer identity selected before node-result commit.
525        timer_id: TimerId,
526        /// Semantic purpose of the timer.
527        timer_kind: RunTimerKind,
528        /// Inclusive earliest database instant at which it may fire.
529        due_at: crate::Timestamp,
530    },
531}
532
533impl NodeWait {
534    /// Constructs a complete interrupt registration specification.
535    #[allow(clippy::too_many_arguments)]
536    #[must_use]
537    pub const fn interrupt(
538        interrupt_id: InterruptId,
539        interrupt_kind: RunInterruptKind,
540        request_payload: JournalPayload,
541        action_digest: Digest,
542        required_principal: Option<PrincipalIdentity>,
543        required_scopes: ScopeSet,
544        expires_at: Option<crate::Timestamp>,
545    ) -> Self {
546        Self::Interrupt {
547            interrupt_id,
548            interrupt_kind,
549            request_payload,
550            action_digest,
551            required_principal,
552            required_scopes,
553            expires_at,
554        }
555    }
556
557    /// Constructs a complete timer registration specification.
558    #[must_use]
559    pub const fn timer(
560        timer_id: TimerId,
561        timer_kind: RunTimerKind,
562        due_at: crate::Timestamp,
563    ) -> Self {
564        Self::Timer {
565            timer_id,
566            timer_kind,
567            due_at,
568        }
569    }
570
571    /// Converts this durable node result into an exact event-bound provider
572    /// registration intent.
573    ///
574    /// The provider still supplies and verifies the authoritative database
575    /// registration time while committing the wait barrier.
576    ///
577    /// # Errors
578    ///
579    /// Returns [`crate::DurableWaitError`] only if canonical intent integrity
580    /// material cannot be encoded.
581    pub fn registration_intent(
582        &self,
583        tenant_id: TenantId,
584        run_id: RunId,
585        event_id: EventId,
586    ) -> Result<WaitRegistrationIntent, crate::DurableWaitError> {
587        match self {
588            Self::Interrupt {
589                interrupt_id,
590                interrupt_kind,
591                request_payload,
592                action_digest,
593                required_principal,
594                required_scopes,
595                expires_at,
596            } => InterruptRequestIntent::new(
597                tenant_id,
598                run_id,
599                *interrupt_id,
600                event_id,
601                *interrupt_kind,
602                request_payload.clone(),
603                *action_digest,
604                required_principal.clone(),
605                required_scopes.clone(),
606                *expires_at,
607            )
608            .map(WaitRegistrationIntent::interrupt),
609            Self::Timer {
610                timer_id,
611                timer_kind,
612                due_at,
613            } => TimerRegistrationIntent::new(
614                tenant_id,
615                run_id,
616                *timer_id,
617                event_id,
618                *timer_kind,
619                *due_at,
620            )
621            .map(WaitRegistrationIntent::timer),
622        }
623    }
624
625    fn identity_uuid(&self) -> uuid::Uuid {
626        match self {
627            Self::Interrupt { interrupt_id, .. } => interrupt_id.into_uuid(),
628            Self::Timer { timer_id, .. } => timer_id.into_uuid(),
629        }
630    }
631}
632
633impl fmt::Debug for NodeWait {
634    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
635        match self {
636            Self::Interrupt {
637                interrupt_id,
638                interrupt_kind,
639                request_payload,
640                action_digest,
641                required_principal,
642                required_scopes,
643                expires_at,
644            } => formatter
645                .debug_struct("NodeWait::Interrupt")
646                .field("interrupt_id", interrupt_id)
647                .field("interrupt_kind", interrupt_kind)
648                .field("request_schema", request_payload.schema())
649                .field("request_digest", &request_payload.digest())
650                .field("action_digest", action_digest)
651                .field("required_principal", required_principal)
652                .field("required_scope_count", &required_scopes.len())
653                .field("expires_at", expires_at)
654                .finish_non_exhaustive(),
655            Self::Timer {
656                timer_id,
657                timer_kind,
658                due_at,
659            } => formatter
660                .debug_struct("NodeWait::Timer")
661                .field("timer_id", timer_id)
662                .field("timer_kind", timer_kind)
663                .field("due_at", due_at)
664                .finish_non_exhaustive(),
665        }
666    }
667}
668
669impl<'de> Deserialize<'de> for NodeWait {
670    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
671    where
672        D: Deserializer<'de>,
673    {
674        #[derive(Deserialize)]
675        #[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
676        #[allow(clippy::large_enum_variant)]
677        enum Wire {
678            Interrupt {
679                interrupt_id: InterruptId,
680                interrupt_kind: RunInterruptKind,
681                request_payload: JournalPayload,
682                action_digest: Digest,
683                required_principal: Option<PrincipalIdentity>,
684                required_scopes: ScopeSet,
685                expires_at: Option<crate::Timestamp>,
686            },
687            Timer {
688                timer_id: TimerId,
689                timer_kind: RunTimerKind,
690                due_at: crate::Timestamp,
691            },
692        }
693
694        Ok(match Wire::deserialize(deserializer)? {
695            Wire::Interrupt {
696                interrupt_id,
697                interrupt_kind,
698                request_payload,
699                action_digest,
700                required_principal,
701                required_scopes,
702                expires_at,
703            } => Self::interrupt(
704                interrupt_id,
705                interrupt_kind,
706                request_payload,
707                action_digest,
708                required_principal,
709                required_scopes,
710                expires_at,
711            ),
712            Wire::Timer {
713                timer_id,
714                timer_kind,
715                due_at,
716            } => Self::timer(timer_id, timer_kind, due_at),
717        })
718    }
719}
720
721/// Non-empty, bounded, identity-unique uncommitted wait batch.
722#[derive(Clone, Eq, PartialEq)]
723pub struct NodeWaits {
724    values: Box<[NodeWait]>,
725}
726
727impl NodeWaits {
728    /// Hard maximum number of conditions one graph barrier may register.
729    pub const MAX_LEN: usize = 64;
730
731    /// Validates one complete wait specification batch.
732    ///
733    /// # Errors
734    ///
735    /// Returns [`NodeWaitsError`] for an empty, oversized, or identity-crossed
736    /// batch.
737    pub fn try_new<I>(values: I) -> Result<Self, NodeWaitsError>
738    where
739        I: IntoIterator<Item = NodeWait>,
740    {
741        let mut collected = Vec::new();
742        for value in values {
743            if collected.len() == Self::MAX_LEN {
744                return Err(NodeWaitsError::TooMany {
745                    maximum: Self::MAX_LEN,
746                    actual: Self::MAX_LEN + 1,
747                });
748            }
749            if collected
750                .iter()
751                .any(|existing: &NodeWait| existing.identity_uuid() == value.identity_uuid())
752            {
753                return Err(NodeWaitsError::DuplicateIdentity);
754            }
755            collected.push(value);
756        }
757        if collected.is_empty() {
758            return Err(NodeWaitsError::Empty);
759        }
760        Ok(Self {
761            values: collected.into_boxed_slice(),
762        })
763    }
764
765    /// Returns the number of conditions in semantic order.
766    #[must_use]
767    pub const fn len(&self) -> usize {
768        self.values.len()
769    }
770
771    /// Returns whether no conditions exist.
772    ///
773    /// This is always `false` for a valid value.
774    #[must_use]
775    pub const fn is_empty(&self) -> bool {
776        self.values.is_empty()
777    }
778
779    /// Iterates uncommitted conditions in deterministic semantic order.
780    pub fn iter(&self) -> impl ExactSizeIterator<Item = &NodeWait> {
781        self.values.iter()
782    }
783
784    /// Converts every condition to an exact registration intent for one
785    /// lifecycle journal event.
786    ///
787    /// # Errors
788    ///
789    /// Returns [`crate::DurableWaitError`] if an intent checksum cannot be
790    /// encoded.
791    pub fn registration_intents(
792        &self,
793        tenant_id: &TenantId,
794        run_id: RunId,
795        event_id: EventId,
796    ) -> Result<Vec<WaitRegistrationIntent>, crate::DurableWaitError> {
797        self.values
798            .iter()
799            .map(|wait| wait.registration_intent(tenant_id.clone(), run_id, event_id))
800            .collect()
801    }
802}
803
804impl fmt::Debug for NodeWaits {
805    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
806        formatter
807            .debug_struct("NodeWaits")
808            .field("count", &self.len())
809            .finish_non_exhaustive()
810    }
811}
812
813impl Serialize for NodeWaits {
814    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
815    where
816        S: Serializer,
817    {
818        self.values.serialize(serializer)
819    }
820}
821
822impl<'de> Deserialize<'de> for NodeWaits {
823    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
824    where
825        D: Deserializer<'de>,
826    {
827        deserializer.deserialize_seq(NodeWaitsVisitor)
828    }
829}
830
831struct NodeWaitsVisitor;
832
833impl<'de> de::Visitor<'de> for NodeWaitsVisitor {
834    type Value = NodeWaits;
835
836    fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
837        write!(
838            formatter,
839            "one to {} unique graph wait specifications",
840            NodeWaits::MAX_LEN
841        )
842    }
843
844    fn visit_seq<A>(self, mut sequence: A) -> Result<Self::Value, A::Error>
845    where
846        A: SeqAccess<'de>,
847    {
848        let mut values = Vec::<NodeWait>::with_capacity(
849            sequence
850                .size_hint()
851                .unwrap_or_default()
852                .min(NodeWaits::MAX_LEN),
853        );
854        while let Some(value) = sequence.next_element::<NodeWait>()? {
855            if values.len() == NodeWaits::MAX_LEN {
856                return Err(de::Error::custom(NodeWaitsError::TooMany {
857                    maximum: NodeWaits::MAX_LEN,
858                    actual: NodeWaits::MAX_LEN + 1,
859                }));
860            }
861            if values
862                .iter()
863                .any(|existing| existing.identity_uuid() == value.identity_uuid())
864            {
865                return Err(de::Error::custom(NodeWaitsError::DuplicateIdentity));
866            }
867            values.push(value);
868        }
869        NodeWaits::try_new(values).map_err(de::Error::custom)
870    }
871}
872
873impl JsonSchema for NodeWaits {
874    fn schema_name() -> std::borrow::Cow<'static, str> {
875        "NodeWaits".into()
876    }
877
878    fn schema_id() -> std::borrow::Cow<'static, str> {
879        concat!(module_path!(), "::NodeWaits").into()
880    }
881
882    fn json_schema(generator: &mut SchemaGenerator) -> Schema {
883        json_schema!({
884            "type": "array",
885            "items": generator.subschema_for::<NodeWait>(),
886            "minItems": 1,
887            "maxItems": 64,
888            "uniqueItems": true,
889            "description": "Complete uncommitted graph wait specifications. UUID identity uniqueness is enforced at runtime."
890        })
891    }
892}
893
894/// Invalid graph wait specification batch.
895#[derive(Clone, Debug, Eq, Error, PartialEq)]
896#[non_exhaustive]
897pub enum NodeWaitsError {
898    /// A suspending node supplied no condition.
899    #[error("a graph wait batch must contain at least one condition")]
900    Empty,
901    /// The hard simultaneous-condition ceiling was exceeded.
902    #[error("graph wait batch has {actual} conditions; hard maximum is {maximum}")]
903    TooMany {
904        /// Absolute simultaneous-condition ceiling.
905        maximum: usize,
906        /// First observed count beyond the ceiling.
907        actual: usize,
908    },
909    /// Two variants reused one UUID identity.
910    #[error("graph wait condition identities must be globally unique")]
911    DuplicateIdentity,
912}
913
914/// Closed control outcome emitted alongside a node's state contribution.
915#[derive(Clone, Debug, Deserialize, Eq, JsonSchema, PartialEq, Serialize)]
916#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
917pub enum NodeControl {
918    /// Follow the node's unconditional compiled edges.
919    Continue,
920    /// Select one declared conditional route.
921    Route {
922        /// Route resolved by the pinned graph definition at the barrier.
923        route_id: RouteId,
924    },
925    /// Suspend the run on a non-empty atomic condition batch.
926    Wait {
927        /// Interrupts and timers to register at the barrier.
928        waits: NodeWaits,
929    },
930    /// Complete the graph with schema-validated output.
931    Terminal {
932        /// Exact successful graph output.
933        output: NodeTerminalOutput,
934    },
935}
936
937impl NodeControl {
938    /// Returns the stable control discriminator.
939    #[must_use]
940    pub const fn kind(&self) -> NodeControlKind {
941        match self {
942            Self::Continue => NodeControlKind::Continue,
943            Self::Route { .. } => NodeControlKind::Route,
944            Self::Wait { .. } => NodeControlKind::Wait,
945            Self::Terminal { .. } => NodeControlKind::Terminal,
946        }
947    }
948}
949
950/// Stable discriminator for one node control result.
951#[derive(
952    Clone, Copy, Debug, Deserialize, Eq, Hash, JsonSchema, Ord, PartialEq, PartialOrd, Serialize,
953)]
954#[serde(rename_all = "snake_case")]
955pub enum NodeControlKind {
956    /// Unconditional compiled edges.
957    Continue,
958    /// Conditional route selection.
959    Route,
960    /// Durable suspension.
961    Wait,
962    /// Successful graph completion.
963    Terminal,
964}
965
966/// Kind of external invocation referenced by a pending node result.
967///
968/// Variant order is the canonical binding sort order.
969#[derive(
970    Clone, Copy, Debug, Deserialize, Eq, Hash, JsonSchema, Ord, PartialEq, PartialOrd, Serialize,
971)]
972#[serde(rename_all = "snake_case")]
973pub enum NodeInvocationBindingKind {
974    /// Model-provider invocation.
975    Model,
976    /// Tool invocation.
977    Tool,
978}
979
980/// Exact terminal external invocation consumed by one node result.
981///
982/// The embedded activation makes cross-node substitution locally detectable.
983/// A durable adapter must additionally reload the exact full invocation
984/// revision and prove that its intent activation equals this value before it
985/// accepts the reference.
986#[derive(Clone, Debug, Eq, JsonSchema, PartialEq, Serialize)]
987#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
988pub enum NodeInvocationBinding {
989    /// Exact terminal model invocation.
990    ///
991    /// Both successful and known-failed model outcomes are consumable when a
992    /// node has deterministic semantics for the failure. Ambiguous or
993    /// unfinished provider outcomes remain ineligible.
994    Model {
995        /// Activation recorded by the full invocation intent.
996        activation: NodeActivation,
997        /// Compact terminal model revision identity.
998        head: ModelInvocationHead,
999    },
1000    /// Exact terminal tool invocation.
1001    ///
1002    /// Both successful and known-failed tool outcomes are consumable: a model
1003    /// transcript must be able to observe a deterministic tool error. Ambiguous
1004    /// or unfinished tool outcomes remain ineligible.
1005    Tool {
1006        /// Activation recorded by the full invocation intent.
1007        activation: NodeActivation,
1008        /// Compact terminal tool revision identity.
1009        head: ToolInvocationHead,
1010    },
1011}
1012
1013impl NodeInvocationBinding {
1014    /// Constructs a binding from a fully validated terminal model invocation.
1015    ///
1016    /// # Errors
1017    ///
1018    /// Returns [`NodeInvocationBindingError`] unless the invocation is
1019    /// committed or known-failed and its journal anchor strictly follows its
1020    /// base checkpoint.
1021    pub fn from_model(invocation: &ModelInvocation) -> Result<Self, NodeInvocationBindingError> {
1022        Self::restore_model(invocation.intent().activation().clone(), invocation.head())
1023    }
1024
1025    /// Constructs a binding from a fully validated terminal tool invocation.
1026    ///
1027    /// # Errors
1028    ///
1029    /// Returns [`NodeInvocationBindingError`] unless the invocation is
1030    /// committed or known-failed and its journal anchor strictly follows its
1031    /// base checkpoint.
1032    pub fn from_tool(invocation: &ToolInvocation) -> Result<Self, NodeInvocationBindingError> {
1033        Self::restore_tool(invocation.intent().activation().clone(), invocation.head())
1034    }
1035
1036    /// Returns the external invocation kind.
1037    #[must_use]
1038    pub const fn kind(&self) -> NodeInvocationBindingKind {
1039        match self {
1040            Self::Model { .. } => NodeInvocationBindingKind::Model,
1041            Self::Tool { .. } => NodeInvocationBindingKind::Tool,
1042        }
1043    }
1044
1045    /// Returns the exact owning node activation.
1046    #[must_use]
1047    pub const fn activation(&self) -> &NodeActivation {
1048        match self {
1049            Self::Model { activation, .. } | Self::Tool { activation, .. } => activation,
1050        }
1051    }
1052
1053    /// Returns the stable logical invocation identity.
1054    #[must_use]
1055    pub const fn invocation_id(&self) -> InvocationId {
1056        match self {
1057            Self::Model { head, .. } => head.invocation_id(),
1058            Self::Tool { head, .. } => head.invocation_id(),
1059        }
1060    }
1061
1062    /// Returns the exact journal head that committed the external result.
1063    #[must_use]
1064    pub const fn journal_head(&self) -> &JournalHead {
1065        match self {
1066            Self::Model { head, .. } => head.journal_head(),
1067            Self::Tool { head, .. } => head.journal_head(),
1068        }
1069    }
1070
1071    /// Returns the model head for a model binding.
1072    #[must_use]
1073    pub const fn model_head(&self) -> Option<&ModelInvocationHead> {
1074        match self {
1075            Self::Model { head, .. } => Some(head),
1076            Self::Tool { .. } => None,
1077        }
1078    }
1079
1080    /// Returns the tool head for a tool binding.
1081    #[must_use]
1082    pub const fn tool_head(&self) -> Option<&ToolInvocationHead> {
1083        match self {
1084            Self::Tool { head, .. } => Some(head),
1085            Self::Model { .. } => None,
1086        }
1087    }
1088
1089    fn restore_model(
1090        activation: NodeActivation,
1091        head: ModelInvocationHead,
1092    ) -> Result<Self, NodeInvocationBindingError> {
1093        if !matches!(
1094            head.status(),
1095            ModelInvocationStatus::Committed | ModelInvocationStatus::Failed
1096        ) {
1097            return Err(NodeInvocationBindingError::ModelNotConsumable {
1098                actual: head.status(),
1099            });
1100        }
1101        validate_binding_scope(
1102            &activation,
1103            head.tenant_id(),
1104            head.run_id(),
1105            head.journal_head(),
1106        )?;
1107        Ok(Self::Model { activation, head })
1108    }
1109
1110    fn restore_tool(
1111        activation: NodeActivation,
1112        head: ToolInvocationHead,
1113    ) -> Result<Self, NodeInvocationBindingError> {
1114        if !matches!(
1115            head.status(),
1116            ToolInvocationStatus::Committed | ToolInvocationStatus::Failed
1117        ) {
1118            return Err(NodeInvocationBindingError::ToolNotConsumable {
1119                actual: head.status(),
1120            });
1121        }
1122        validate_binding_scope(
1123            &activation,
1124            head.tenant_id(),
1125            head.run_id(),
1126            head.journal_head(),
1127        )?;
1128        Ok(Self::Tool { activation, head })
1129    }
1130}
1131
1132impl<'de> Deserialize<'de> for NodeInvocationBinding {
1133    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1134    where
1135        D: Deserializer<'de>,
1136    {
1137        #[derive(Deserialize)]
1138        #[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
1139        enum Wire {
1140            Model {
1141                activation: NodeActivation,
1142                head: ModelInvocationHead,
1143            },
1144            Tool {
1145                activation: NodeActivation,
1146                head: ToolInvocationHead,
1147            },
1148        }
1149
1150        match Wire::deserialize(deserializer)? {
1151            Wire::Model { activation, head } => Self::restore_model(activation, head),
1152            Wire::Tool { activation, head } => Self::restore_tool(activation, head),
1153        }
1154        .map_err(de::Error::custom)
1155    }
1156}
1157
1158/// Invalid external invocation binding.
1159#[derive(Clone, Debug, Eq, Error, PartialEq)]
1160#[non_exhaustive]
1161pub enum NodeInvocationBindingError {
1162    /// Model revision was neither successful nor a known failure.
1163    #[error(
1164        "model invocation binding must reference committed or known-failed state, got {actual:?}"
1165    )]
1166    ModelNotConsumable {
1167        /// Rejected lifecycle status.
1168        actual: ModelInvocationStatus,
1169    },
1170    /// Tool revision was neither successful nor a known failure.
1171    #[error(
1172        "tool invocation binding must reference committed or known-failed state, got {actual:?}"
1173    )]
1174    ToolNotConsumable {
1175        /// Rejected lifecycle status.
1176        actual: ToolInvocationStatus,
1177    },
1178    /// Invocation head crossed the activation tenant boundary.
1179    #[error("invocation binding crosses its activation tenant boundary")]
1180    TenantMismatch,
1181    /// Invocation head named another run.
1182    #[error("invocation binding does not belong to its activation run")]
1183    RunMismatch,
1184    /// Invocation result did not advance the activation's base journal.
1185    #[error("invocation binding journal does not follow its activation base checkpoint")]
1186    JournalNotAfterBase,
1187    /// Invocation result time preceded its activation base checkpoint.
1188    #[error("invocation binding clock precedes its activation base checkpoint")]
1189    ClockRegression,
1190}
1191
1192fn validate_binding_scope(
1193    activation: &NodeActivation,
1194    tenant_id: &TenantId,
1195    run_id: RunId,
1196    journal_head: &JournalHead,
1197) -> Result<(), NodeInvocationBindingError> {
1198    if tenant_id != activation.tenant_id() || journal_head.tenant_id() != activation.tenant_id() {
1199        return Err(NodeInvocationBindingError::TenantMismatch);
1200    }
1201    if run_id != activation.run_id() || journal_head.run_id() != activation.run_id() {
1202        return Err(NodeInvocationBindingError::RunMismatch);
1203    }
1204    let base = activation.base_checkpoint().journal_head();
1205    if journal_head.sequence() <= base.sequence() {
1206        return Err(NodeInvocationBindingError::JournalNotAfterBase);
1207    }
1208    if journal_head.recorded_at() < base.recorded_at() {
1209        return Err(NodeInvocationBindingError::ClockRegression);
1210    }
1211    Ok(())
1212}
1213
1214/// Canonically ordered, duplicate-free, bounded external invocation bindings.
1215#[derive(Clone, Debug, Default, Eq, PartialEq)]
1216pub struct NodeInvocationBindings(Box<[NodeInvocationBinding]>);
1217
1218impl NodeInvocationBindings {
1219    /// Maximum external invocation references in one pending result.
1220    pub const MAX_LEN: usize = 256;
1221
1222    /// Constructs an empty binding collection.
1223    #[must_use]
1224    pub fn empty() -> Self {
1225        Self::default()
1226    }
1227
1228    /// Validates activation ownership, uniqueness, and the hard count ceiling.
1229    ///
1230    /// Values are serialized in canonical `(kind, invocation_id)` order.
1231    ///
1232    /// # Errors
1233    ///
1234    /// Returns [`NodeInvocationBindingsError`] for a crossed activation,
1235    /// duplicate logical invocation, or more than [`Self::MAX_LEN`] entries.
1236    pub fn try_new<I>(
1237        activation: &NodeActivation,
1238        values: I,
1239    ) -> Result<Self, NodeInvocationBindingsError>
1240    where
1241        I: IntoIterator<Item = NodeInvocationBinding>,
1242    {
1243        let values = collect_bindings(values)?;
1244        validate_bindings_activation(activation, &values)?;
1245        Ok(Self(values.into_boxed_slice()))
1246    }
1247
1248    /// Returns the number of external invocation references.
1249    #[must_use]
1250    pub const fn len(&self) -> usize {
1251        self.0.len()
1252    }
1253
1254    /// Returns whether no external invocation was consumed.
1255    #[must_use]
1256    pub const fn is_empty(&self) -> bool {
1257        self.0.is_empty()
1258    }
1259
1260    /// Iterates bindings in canonical identity order.
1261    #[must_use]
1262    pub fn iter(&self) -> impl ExactSizeIterator<Item = &NodeInvocationBinding> {
1263        self.0.iter()
1264    }
1265}
1266
1267impl Serialize for NodeInvocationBindings {
1268    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1269    where
1270        S: Serializer,
1271    {
1272        self.0.serialize(serializer)
1273    }
1274}
1275
1276impl<'de> Deserialize<'de> for NodeInvocationBindings {
1277    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1278    where
1279        D: Deserializer<'de>,
1280    {
1281        deserializer.deserialize_seq(NodeInvocationBindingsVisitor)
1282    }
1283}
1284
1285struct NodeInvocationBindingsVisitor;
1286
1287impl<'de> de::Visitor<'de> for NodeInvocationBindingsVisitor {
1288    type Value = NodeInvocationBindings;
1289
1290    fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1291        write!(
1292            formatter,
1293            "at most {} unique terminal node invocation bindings",
1294            NodeInvocationBindings::MAX_LEN
1295        )
1296    }
1297
1298    fn visit_seq<A>(self, mut sequence: A) -> Result<Self::Value, A::Error>
1299    where
1300        A: SeqAccess<'de>,
1301    {
1302        let mut values = Vec::with_capacity(
1303            sequence
1304                .size_hint()
1305                .unwrap_or_default()
1306                .min(NodeInvocationBindings::MAX_LEN),
1307        );
1308        while let Some(value) = sequence.next_element::<NodeInvocationBinding>()? {
1309            if values.len() == NodeInvocationBindings::MAX_LEN {
1310                return Err(de::Error::custom(NodeInvocationBindingsError::TooMany {
1311                    maximum: NodeInvocationBindings::MAX_LEN,
1312                    actual: NodeInvocationBindings::MAX_LEN + 1,
1313                }));
1314            }
1315            values.push(value);
1316        }
1317        let values = collect_bindings(values).map_err(de::Error::custom)?;
1318        if let Some(first) = values.first() {
1319            validate_bindings_activation(first.activation(), &values).map_err(de::Error::custom)?;
1320        }
1321        Ok(NodeInvocationBindings(values.into_boxed_slice()))
1322    }
1323}
1324
1325impl JsonSchema for NodeInvocationBindings {
1326    fn schema_name() -> std::borrow::Cow<'static, str> {
1327        "NodeInvocationBindings".into()
1328    }
1329
1330    fn schema_id() -> std::borrow::Cow<'static, str> {
1331        concat!(module_path!(), "::NodeInvocationBindings").into()
1332    }
1333
1334    fn json_schema(generator: &mut SchemaGenerator) -> Schema {
1335        json_schema!({
1336            "type": "array",
1337            "items": generator.subschema_for::<NodeInvocationBinding>(),
1338            "maxItems": 256,
1339            "uniqueItems": true,
1340            "description": "Serialized in canonical (kind, invocation_id) order; runtime additionally requires one exact node activation."
1341        })
1342    }
1343}
1344
1345/// Invalid pending-result invocation collection.
1346#[derive(Clone, Debug, Eq, Error, PartialEq)]
1347#[non_exhaustive]
1348pub enum NodeInvocationBindingsError {
1349    /// The hard reference ceiling was exceeded.
1350    #[error("node invocation bindings contain {actual} entries; maximum is {maximum}")]
1351    TooMany {
1352        /// Absolute maximum.
1353        maximum: usize,
1354        /// First observed count beyond the maximum.
1355        actual: usize,
1356    },
1357    /// The same invocation kind and logical ID appeared more than once.
1358    #[error("node invocation bindings contain a duplicate {kind:?} invocation {invocation_id}")]
1359    Duplicate {
1360        /// Duplicated invocation kind.
1361        kind: NodeInvocationBindingKind,
1362        /// Duplicated invocation identity.
1363        invocation_id: InvocationId,
1364    },
1365    /// A binding belonged to another logical node activation.
1366    #[error("node invocation binding does not belong to the pending result activation")]
1367    ActivationMismatch,
1368}
1369
1370fn collect_bindings<I>(values: I) -> Result<Vec<NodeInvocationBinding>, NodeInvocationBindingsError>
1371where
1372    I: IntoIterator<Item = NodeInvocationBinding>,
1373{
1374    let mut collected = Vec::new();
1375    let mut identities = BTreeSet::new();
1376    for value in values {
1377        if collected.len() == NodeInvocationBindings::MAX_LEN {
1378            return Err(NodeInvocationBindingsError::TooMany {
1379                maximum: NodeInvocationBindings::MAX_LEN,
1380                actual: NodeInvocationBindings::MAX_LEN + 1,
1381            });
1382        }
1383        let identity = (value.kind(), value.invocation_id());
1384        if !identities.insert(identity) {
1385            return Err(NodeInvocationBindingsError::Duplicate {
1386                kind: identity.0,
1387                invocation_id: identity.1,
1388            });
1389        }
1390        collected.push(value);
1391    }
1392    collected.sort_unstable_by_key(|value| (value.kind(), value.invocation_id()));
1393    Ok(collected)
1394}
1395
1396fn validate_bindings_activation(
1397    activation: &NodeActivation,
1398    values: &[NodeInvocationBinding],
1399) -> Result<(), NodeInvocationBindingsError> {
1400    if values
1401        .iter()
1402        .any(|binding| binding.activation() != activation)
1403    {
1404        return Err(NodeInvocationBindingsError::ActivationMismatch);
1405    }
1406    Ok(())
1407}
1408
1409/// Immutable semantic result for one logical node activation before commit.
1410///
1411/// Its checksum deliberately excludes worker fence and journal position. This
1412/// is the idempotency fingerprint: the same logical result may be returned
1413/// after a lost acknowledgement, while any changed update, control outcome, or
1414/// external observation is a conflict.
1415#[derive(Clone, Eq, JsonSchema, PartialEq, Serialize)]
1416#[serde(deny_unknown_fields)]
1417pub struct PendingNodeResultIntent {
1418    activation: NodeActivation,
1419    state_change: NodeStateChange,
1420    control: NodeControl,
1421    bindings: NodeInvocationBindings,
1422    #[serde(skip_serializing_if = "Option::is_none")]
1423    child_join: Option<Box<crate::ChildRunJoinHead>>,
1424    intent_digest: Digest,
1425}
1426
1427impl PendingNodeResultIntent {
1428    /// Constructs and checksums a semantic pending result.
1429    ///
1430    /// # Errors
1431    ///
1432    /// Returns [`PendingNodeResultIntentError`] for a crossed invocation
1433    /// activation or canonical integrity failure.
1434    pub fn new(
1435        activation: NodeActivation,
1436        state_change: NodeStateChange,
1437        control: NodeControl,
1438        bindings: NodeInvocationBindings,
1439    ) -> Result<Self, PendingNodeResultIntentError> {
1440        validate_bindings_activation(&activation, &bindings.0)
1441            .map_err(PendingNodeResultIntentError::bindings)?;
1442        let intent_digest = compute_intent_digest(&PendingNodeResultIntentDigestWire {
1443            activation: &activation,
1444            state_change: &state_change,
1445            control: &control,
1446            bindings: &bindings,
1447            child_join: None,
1448        })?;
1449        Ok(Self {
1450            activation,
1451            state_change,
1452            control,
1453            bindings,
1454            child_join: None,
1455            intent_digest,
1456        })
1457    }
1458
1459    /// Restores a durable semantic result and verifies its checksum.
1460    ///
1461    /// # Errors
1462    ///
1463    /// Returns [`PendingNodeResultIntentError`] for invariant or checksum
1464    /// failure.
1465    pub fn restore(
1466        activation: NodeActivation,
1467        state_change: NodeStateChange,
1468        control: NodeControl,
1469        bindings: NodeInvocationBindings,
1470        intent_digest: Digest,
1471    ) -> Result<Self, PendingNodeResultIntentError> {
1472        let restored = Self::new(activation, state_change, control, bindings)?;
1473        if restored.intent_digest != intent_digest {
1474            return Err(PendingNodeResultIntentError::DigestMismatch);
1475        }
1476        Ok(restored)
1477    }
1478
1479    /// Returns the exact logical node activation.
1480    #[must_use]
1481    pub const fn activation(&self) -> &NodeActivation {
1482        &self.activation
1483    }
1484
1485    /// Returns the typed state contribution.
1486    #[must_use]
1487    pub const fn state_change(&self) -> &NodeStateChange {
1488        &self.state_change
1489    }
1490
1491    /// Returns the explicit control outcome.
1492    #[must_use]
1493    pub const fn control(&self) -> &NodeControl {
1494        &self.control
1495    }
1496
1497    /// Returns committed external invocation bindings.
1498    #[must_use]
1499    pub const fn bindings(&self) -> &NodeInvocationBindings {
1500        &self.bindings
1501    }
1502
1503    /// Binds a published child Join to this exact logical result. The store must
1504    /// authenticate publication and atomically record consumption at commit.
1505    pub fn with_child_join(
1506        mut self,
1507        head: crate::ChildRunJoinHead,
1508    ) -> Result<Self, PendingNodeResultIntentError> {
1509        if head.activation() != &self.activation {
1510            return Err(PendingNodeResultIntentError::ChildJoinScope);
1511        }
1512        self.child_join = Some(Box::new(head));
1513        self.intent_digest = compute_intent_digest(&PendingNodeResultIntentDigestWire {
1514            activation: &self.activation,
1515            state_change: &self.state_change,
1516            control: &self.control,
1517            bindings: &self.bindings,
1518            child_join: self.child_join.as_deref(),
1519        })?;
1520        Ok(self)
1521    }
1522
1523    /// Returns dedicated child evidence, independent of external invocations.
1524    #[must_use]
1525    pub fn child_join(&self) -> Option<&crate::ChildRunJoinHead> {
1526        self.child_join.as_deref()
1527    }
1528
1529    /// Returns the semantic idempotency fingerprint.
1530    #[must_use]
1531    pub const fn intent_digest(&self) -> Digest {
1532        self.intent_digest
1533    }
1534
1535    /// Returns the tenant boundary inherited from the activation.
1536    #[must_use]
1537    pub const fn tenant_id(&self) -> &TenantId {
1538        self.activation.tenant_id()
1539    }
1540
1541    /// Returns the run identity inherited from the activation.
1542    #[must_use]
1543    pub const fn run_id(&self) -> RunId {
1544        self.activation.run_id()
1545    }
1546}
1547
1548impl fmt::Debug for PendingNodeResultIntent {
1549    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1550        formatter
1551            .debug_struct("PendingNodeResultIntent")
1552            .field("activation", &self.activation)
1553            .field("state_change", &self.state_change)
1554            .field("control", &self.control)
1555            .field("binding_count", &self.bindings.len())
1556            .field("intent_digest", &self.intent_digest)
1557            .finish_non_exhaustive()
1558    }
1559}
1560
1561impl<'de> Deserialize<'de> for PendingNodeResultIntent {
1562    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1563    where
1564        D: Deserializer<'de>,
1565    {
1566        #[derive(Deserialize)]
1567        #[serde(deny_unknown_fields)]
1568        struct Wire {
1569            activation: NodeActivation,
1570            state_change: NodeStateChange,
1571            control: NodeControl,
1572            bindings: NodeInvocationBindings,
1573            #[serde(default)]
1574            child_join: Option<crate::ChildRunJoinHead>,
1575            intent_digest: Digest,
1576        }
1577
1578        let wire = Wire::deserialize(deserializer)?;
1579        let mut result = Self::new(
1580            wire.activation,
1581            wire.state_change,
1582            wire.control,
1583            wire.bindings,
1584        )
1585        .map_err(de::Error::custom)?;
1586        if let Some(head) = wire.child_join {
1587            result = result.with_child_join(head).map_err(de::Error::custom)?;
1588        }
1589        if result.intent_digest != wire.intent_digest {
1590            return Err(de::Error::custom(
1591                PendingNodeResultIntentError::DigestMismatch,
1592            ));
1593        }
1594        Ok(result)
1595    }
1596}
1597
1598/// Invalid or corrupted pending node-result intent.
1599#[derive(Clone, Debug, Eq, Error, PartialEq)]
1600#[non_exhaustive]
1601pub enum PendingNodeResultIntentError {
1602    /// Child publication belongs to another logical activation.
1603    #[error("pending node result child Join activation mismatch")]
1604    ChildJoinScope,
1605    /// An external invocation reference crossed the node activation boundary.
1606    #[error("pending node result has invalid invocation bindings: {source}")]
1607    Bindings {
1608        /// Exact collection failure.
1609        #[source]
1610        source: NodeInvocationBindingsError,
1611    },
1612    /// Canonical integrity material could not be produced.
1613    #[error("pending node result intent integrity calculation failed: {source}")]
1614    Integrity {
1615        /// Exact integrity failure.
1616        #[source]
1617        source: PendingNodeResultIntegrityError,
1618    },
1619    /// Persisted semantic checksum did not match caller-controlled fields.
1620    #[error("pending node result intent digest does not match its fields")]
1621    DigestMismatch,
1622}
1623
1624impl PendingNodeResultIntentError {
1625    const fn bindings(source: NodeInvocationBindingsError) -> Self {
1626        Self::Bindings { source }
1627    }
1628}
1629
1630impl From<PendingNodeResultIntegrityError> for PendingNodeResultIntentError {
1631    fn from(source: PendingNodeResultIntegrityError) -> Self {
1632        Self::Integrity { source }
1633    }
1634}
1635
1636/// One immutable, worker-fenced and journal-anchored pending node result.
1637///
1638/// Storage must compare the exact live fence and base checkpoint under the run
1639/// lock, append the result journal event, and insert this record in one
1640/// transaction. A barrier later consumes the record into one successor
1641/// checkpoint; consumption never mutates these integrity-bearing fields.
1642#[derive(Clone, Eq, JsonSchema, PartialEq, Serialize)]
1643#[serde(deny_unknown_fields)]
1644pub struct PendingNodeResult {
1645    intent: PendingNodeResultIntent,
1646    fence: RunFence,
1647    journal_head: JournalHead,
1648    digest: Digest,
1649}
1650
1651impl PendingNodeResult {
1652    /// Materializes a semantic result after its worker journal event commits.
1653    ///
1654    /// # Errors
1655    ///
1656    /// Returns [`PendingNodeResultError`] for crossed scope, stale ordering, or
1657    /// integrity failure.
1658    pub fn commit(
1659        intent: PendingNodeResultIntent,
1660        fence: RunFence,
1661        journal_head: JournalHead,
1662    ) -> Result<Self, PendingNodeResultError> {
1663        validate_result_shape(&intent, &fence, &journal_head)?;
1664        let digest = compute_record_digest(&PendingNodeResultDigestWire {
1665            intent_digest: intent.intent_digest,
1666            fence: &fence,
1667            journal_head: &journal_head,
1668        })?;
1669        Ok(Self {
1670            intent,
1671            fence,
1672            journal_head,
1673            digest,
1674        })
1675    }
1676
1677    /// Restores a durable pending result and verifies every local invariant.
1678    ///
1679    /// Durable adapters must additionally verify the exact base checkpoint,
1680    /// full external invocation revisions, journal event source, and live or
1681    /// historical lease facts from their authoritative tables.
1682    ///
1683    /// # Errors
1684    ///
1685    /// Returns [`PendingNodeResultError`] for invariant or checksum failure.
1686    pub fn restore(
1687        intent: PendingNodeResultIntent,
1688        fence: RunFence,
1689        journal_head: JournalHead,
1690        digest: Digest,
1691    ) -> Result<Self, PendingNodeResultError> {
1692        let restored = Self::commit(intent, fence, journal_head)?;
1693        if restored.digest != digest {
1694            return Err(PendingNodeResultError::DigestMismatch);
1695        }
1696        Ok(restored)
1697    }
1698
1699    /// Returns the immutable semantic intent.
1700    #[must_use]
1701    pub const fn intent(&self) -> &PendingNodeResultIntent {
1702        &self.intent
1703    }
1704
1705    /// Returns the physical worker and fencing epoch that won the commit.
1706    #[must_use]
1707    pub const fn fence(&self) -> &RunFence {
1708        &self.fence
1709    }
1710
1711    /// Returns the exact journal prefix anchoring this result.
1712    #[must_use]
1713    pub const fn journal_head(&self) -> &JournalHead {
1714        &self.journal_head
1715    }
1716
1717    /// Returns the complete domain-separated record checksum.
1718    #[must_use]
1719    pub const fn digest(&self) -> Digest {
1720        self.digest
1721    }
1722
1723    /// Returns a compact exact comparison and consumption token.
1724    #[must_use]
1725    pub fn head(&self) -> PendingNodeResultHead {
1726        PendingNodeResultHead {
1727            activation: self.intent.activation.clone(),
1728            intent_digest: self.intent.intent_digest,
1729            fence: self.fence.clone(),
1730            journal_head: self.journal_head.clone(),
1731            digest: self.digest,
1732        }
1733    }
1734}
1735
1736impl fmt::Debug for PendingNodeResult {
1737    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1738        formatter
1739            .debug_struct("PendingNodeResult")
1740            .field("intent", &self.intent)
1741            .field("fence", &self.fence)
1742            .field("journal_head", &self.journal_head)
1743            .field("digest", &self.digest)
1744            .finish_non_exhaustive()
1745    }
1746}
1747
1748impl<'de> Deserialize<'de> for PendingNodeResult {
1749    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1750    where
1751        D: Deserializer<'de>,
1752    {
1753        #[derive(Deserialize)]
1754        #[serde(deny_unknown_fields)]
1755        struct Wire {
1756            intent: PendingNodeResultIntent,
1757            fence: RunFence,
1758            journal_head: JournalHead,
1759            digest: Digest,
1760        }
1761
1762        let wire = Wire::deserialize(deserializer)?;
1763        Self::restore(wire.intent, wire.fence, wire.journal_head, wire.digest)
1764            .map_err(de::Error::custom)
1765    }
1766}
1767
1768/// Compact exact identity of one pending node result.
1769#[derive(Clone, Debug, Eq, JsonSchema, PartialEq, Serialize)]
1770#[serde(deny_unknown_fields)]
1771pub struct PendingNodeResultHead {
1772    activation: NodeActivation,
1773    intent_digest: Digest,
1774    fence: RunFence,
1775    journal_head: JournalHead,
1776    digest: Digest,
1777}
1778
1779impl PendingNodeResultHead {
1780    /// Constructs a trusted compact head while enforcing scope and base order.
1781    ///
1782    /// Obtain heads from [`PendingNodeResult::head`] unless restoring verified
1783    /// durable metadata.
1784    ///
1785    /// # Errors
1786    ///
1787    /// Returns [`PendingNodeResultError`] for crossed scope or a journal anchor
1788    /// that does not follow the activation checkpoint.
1789    pub fn new(
1790        activation: NodeActivation,
1791        intent_digest: Digest,
1792        fence: RunFence,
1793        journal_head: JournalHead,
1794        digest: Digest,
1795    ) -> Result<Self, PendingNodeResultError> {
1796        validate_basic_result_scope(&activation, &fence, &journal_head)?;
1797        Ok(Self {
1798            activation,
1799            intent_digest,
1800            fence,
1801            journal_head,
1802            digest,
1803        })
1804    }
1805
1806    /// Returns the exact logical activation.
1807    #[must_use]
1808    pub const fn activation(&self) -> &NodeActivation {
1809        &self.activation
1810    }
1811
1812    /// Returns the semantic idempotency fingerprint.
1813    #[must_use]
1814    pub const fn intent_digest(&self) -> Digest {
1815        self.intent_digest
1816    }
1817
1818    /// Returns the winning physical worker fence.
1819    #[must_use]
1820    pub const fn fence(&self) -> &RunFence {
1821        &self.fence
1822    }
1823
1824    /// Returns the result's exact journal anchor.
1825    #[must_use]
1826    pub const fn journal_head(&self) -> &JournalHead {
1827        &self.journal_head
1828    }
1829
1830    /// Returns the exact record checksum.
1831    #[must_use]
1832    pub const fn digest(&self) -> Digest {
1833        self.digest
1834    }
1835}
1836
1837impl<'de> Deserialize<'de> for PendingNodeResultHead {
1838    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1839    where
1840        D: Deserializer<'de>,
1841    {
1842        #[derive(Deserialize)]
1843        #[serde(deny_unknown_fields)]
1844        struct Wire {
1845            activation: NodeActivation,
1846            intent_digest: Digest,
1847            fence: RunFence,
1848            journal_head: JournalHead,
1849            digest: Digest,
1850        }
1851
1852        let wire = Wire::deserialize(deserializer)?;
1853        Self::new(
1854            wire.activation,
1855            wire.intent_digest,
1856            wire.fence,
1857            wire.journal_head,
1858            wire.digest,
1859        )
1860        .map_err(de::Error::custom)
1861    }
1862}
1863
1864/// Invalid or corrupted pending node-result record.
1865#[derive(Clone, Debug, Eq, Error, PartialEq)]
1866#[non_exhaustive]
1867pub enum PendingNodeResultError {
1868    /// Worker fence crossed the activation tenant boundary.
1869    #[error("pending node result fence crosses the activation tenant boundary")]
1870    FenceTenantMismatch,
1871    /// Worker fence named another run.
1872    #[error("pending node result fence does not belong to the activation run")]
1873    FenceRunMismatch,
1874    /// Journal head crossed the activation tenant boundary.
1875    #[error("pending node result journal crosses the activation tenant boundary")]
1876    JournalTenantMismatch,
1877    /// Journal head named another run.
1878    #[error("pending node result journal does not belong to the activation run")]
1879    JournalRunMismatch,
1880    /// Result journal did not strictly follow the base checkpoint.
1881    #[error("pending node result journal does not follow its base checkpoint")]
1882    JournalNotAfterBase,
1883    /// Result durable time preceded the base checkpoint.
1884    #[error("pending node result clock precedes its base checkpoint")]
1885    ClockRegression,
1886    /// Result journal did not strictly follow every bound external result.
1887    #[error("pending node result journal does not follow every invocation binding")]
1888    JournalNotAfterBinding,
1889    /// Result durable time preceded a bound external result.
1890    #[error("pending node result clock precedes an invocation binding")]
1891    BindingClockRegression,
1892    /// Canonical integrity material could not be produced.
1893    #[error("pending node result integrity calculation failed: {source}")]
1894    Integrity {
1895        /// Exact integrity failure.
1896        #[source]
1897        source: PendingNodeResultIntegrityError,
1898    },
1899    /// Persisted record checksum did not match its fields.
1900    #[error("pending node result digest does not match its fields")]
1901    DigestMismatch,
1902}
1903
1904impl From<PendingNodeResultIntegrityError> for PendingNodeResultError {
1905    fn from(source: PendingNodeResultIntegrityError) -> Self {
1906        Self::Integrity { source }
1907    }
1908}
1909
1910fn validate_result_shape(
1911    intent: &PendingNodeResultIntent,
1912    fence: &RunFence,
1913    journal_head: &JournalHead,
1914) -> Result<(), PendingNodeResultError> {
1915    validate_basic_result_scope(intent.activation(), fence, journal_head)?;
1916    if let Some(join) = intent.child_join() {
1917        if journal_head.sequence() <= join.journal_head().sequence() {
1918            return Err(PendingNodeResultError::JournalNotAfterBinding);
1919        }
1920        if journal_head.recorded_at() < join.journal_head().recorded_at() {
1921            return Err(PendingNodeResultError::BindingClockRegression);
1922        }
1923    }
1924    for binding in intent.bindings().iter() {
1925        if journal_head.sequence() <= binding.journal_head().sequence() {
1926            return Err(PendingNodeResultError::JournalNotAfterBinding);
1927        }
1928        if journal_head.recorded_at() < binding.journal_head().recorded_at() {
1929            return Err(PendingNodeResultError::BindingClockRegression);
1930        }
1931    }
1932    Ok(())
1933}
1934
1935fn validate_basic_result_scope(
1936    activation: &NodeActivation,
1937    fence: &RunFence,
1938    journal_head: &JournalHead,
1939) -> Result<(), PendingNodeResultError> {
1940    if fence.tenant_id() != activation.tenant_id() {
1941        return Err(PendingNodeResultError::FenceTenantMismatch);
1942    }
1943    if fence.run_id() != activation.run_id() {
1944        return Err(PendingNodeResultError::FenceRunMismatch);
1945    }
1946    if journal_head.tenant_id() != activation.tenant_id() {
1947        return Err(PendingNodeResultError::JournalTenantMismatch);
1948    }
1949    if journal_head.run_id() != activation.run_id() {
1950        return Err(PendingNodeResultError::JournalRunMismatch);
1951    }
1952    let base = activation.base_checkpoint().journal_head();
1953    if journal_head.sequence() <= base.sequence() {
1954        return Err(PendingNodeResultError::JournalNotAfterBase);
1955    }
1956    if journal_head.recorded_at() < base.recorded_at() {
1957        return Err(PendingNodeResultError::ClockRegression);
1958    }
1959    Ok(())
1960}
1961
1962#[derive(Serialize)]
1963struct SchemaPayloadDigestWire<'a> {
1964    schema: &'a SchemaReference,
1965    data_digest: Digest,
1966}
1967
1968#[derive(Serialize)]
1969struct PendingNodeResultIntentDigestWire<'a> {
1970    activation: &'a NodeActivation,
1971    state_change: &'a NodeStateChange,
1972    control: &'a NodeControl,
1973    bindings: &'a NodeInvocationBindings,
1974    #[serde(skip_serializing_if = "Option::is_none")]
1975    child_join: Option<&'a crate::ChildRunJoinHead>,
1976}
1977
1978#[derive(Serialize)]
1979struct PendingNodeResultDigestWire<'a> {
1980    intent_digest: Digest,
1981    fence: &'a RunFence,
1982    journal_head: &'a JournalHead,
1983}
1984
1985fn compute_payload_digest(
1986    domain: &[u8],
1987    schema: &SchemaReference,
1988    data: &BoundedJson,
1989) -> Result<Digest, PendingNodeResultIntegrityError> {
1990    let canonical = CanonicalJson::new(data)
1991        .map_err(|source| PendingNodeResultIntegrityError::PayloadCanonicalization { source })?;
1992    domain_separated_digest(
1993        domain,
1994        &SchemaPayloadDigestWire {
1995            schema,
1996            data_digest: canonical.digest(),
1997        },
1998    )
1999}
2000
2001fn compute_intent_digest(
2002    value: &PendingNodeResultIntentDigestWire<'_>,
2003) -> Result<Digest, PendingNodeResultIntegrityError> {
2004    domain_separated_digest(INTENT_DIGEST_DOMAIN, value)
2005}
2006
2007fn compute_record_digest(
2008    value: &PendingNodeResultDigestWire<'_>,
2009) -> Result<Digest, PendingNodeResultIntegrityError> {
2010    domain_separated_digest(RECORD_DIGEST_DOMAIN, value)
2011}
2012
2013fn domain_separated_digest<T: Serialize>(
2014    domain: &[u8],
2015    value: &T,
2016) -> Result<Digest, PendingNodeResultIntegrityError> {
2017    let canonical = serde_json_canonicalizer::to_vec(value)
2018        .map_err(|_| PendingNodeResultIntegrityError::CanonicalSerialization)?;
2019    let mut preimage = Vec::with_capacity(domain.len() + canonical.len());
2020    preimage.extend_from_slice(domain);
2021    preimage.extend_from_slice(&canonical);
2022    Ok(Digest::sha256(preimage))
2023}
2024
2025/// Failure to canonicalize pending node-result integrity material.
2026#[derive(Clone, Debug, Eq, Error, PartialEq)]
2027#[non_exhaustive]
2028pub enum PendingNodeResultIntegrityError {
2029    /// A schema-pinned payload was not RFC 8785 interoperable.
2030    #[error("node result payload canonicalization failed: {source}")]
2031    PayloadCanonicalization {
2032        /// Exact canonical JSON failure.
2033        #[source]
2034        source: CanonicalJsonError,
2035    },
2036    /// A closed typed checksum preimage could not be canonicalized.
2037    #[error("pending node result checksum preimage serialization failed")]
2038    CanonicalSerialization,
2039}
2040
2041#[cfg(test)]
2042mod tests {
2043    use super::*;
2044    use crate::{
2045        AttemptId, Checkpoint, EventId, FencingEpoch, JournalSequence, ModelInvocationRevision,
2046        NodeId, RunTimerKind, TimerId, Timestamp, ToolInvocationRevision,
2047    };
2048    use serde_json::{Value, from_value, json, to_value};
2049
2050    fn checkpoint() -> Checkpoint {
2051        let fixture: Value =
2052            serde_json::from_str(include_str!("../tests/fixtures/core-checkpoint-v1.json"))
2053                .unwrap();
2054        from_value(fixture["checkpoints"][0].clone()).unwrap()
2055    }
2056
2057    fn node_activation(node: &str) -> NodeActivation {
2058        NodeActivation::new(
2059            checkpoint().head(),
2060            crate::GraphNamespace::root(),
2061            NodeId::new(node).unwrap(),
2062            Digest::sha256(format!("{node}-input")),
2063        )
2064    }
2065
2066    fn invocation_id(suffix: &str) -> InvocationId {
2067        format!("01912345-6789-7abc-8def-0123456789{suffix}")
2068            .parse()
2069            .unwrap()
2070    }
2071
2072    fn attempt_id(suffix: &str) -> AttemptId {
2073        format!("01912345-6789-7abc-8def-0123456789{suffix}")
2074            .parse()
2075            .unwrap()
2076    }
2077
2078    fn journal(activation: &NodeActivation, sequence: u64) -> JournalHead {
2079        let base = activation.base_checkpoint().journal_head();
2080        let recorded_at = Timestamp::from_unix_micros(
2081            base.recorded_at().unix_micros() + i64::try_from(sequence - 1).unwrap() * 1_000_000,
2082        )
2083        .unwrap();
2084        let event_id: EventId =
2085            format!("01912345-6789-7abc-8def-0123456789{:02x}", 0xd0 + sequence)
2086                .parse()
2087                .unwrap();
2088        JournalHead::new(
2089            activation.tenant_id().clone(),
2090            activation.run_id(),
2091            JournalSequence::new(sequence).unwrap(),
2092            event_id,
2093            recorded_at,
2094            Digest::sha256(sequence.to_be_bytes()),
2095        )
2096    }
2097
2098    fn fence(activation: &NodeActivation, suffix: &str, epoch: u64) -> RunFence {
2099        RunFence::new(
2100            activation.tenant_id().clone(),
2101            activation.run_id(),
2102            attempt_id(suffix),
2103            FencingEpoch::new(epoch).unwrap(),
2104        )
2105    }
2106
2107    fn model_binding(activation: &NodeActivation) -> NodeInvocationBinding {
2108        let head = ModelInvocationHead::new(
2109            activation.tenant_id().clone(),
2110            activation.run_id(),
2111            invocation_id("d1"),
2112            ModelInvocationRevision::new(2).unwrap(),
2113            ModelInvocationStatus::Committed,
2114            Some(attempt_id("a1")),
2115            journal(activation, 2),
2116            Digest::sha256(b"model-record"),
2117        )
2118        .unwrap();
2119        NodeInvocationBinding::restore_model(activation.clone(), head).unwrap()
2120    }
2121
2122    fn tool_binding(activation: &NodeActivation) -> NodeInvocationBinding {
2123        let head = ToolInvocationHead::new(
2124            activation.tenant_id().clone(),
2125            activation.run_id(),
2126            invocation_id("d2"),
2127            ToolInvocationRevision::new(2).unwrap(),
2128            ToolInvocationStatus::Committed,
2129            Some(attempt_id("a2")),
2130            journal(activation, 3),
2131            Digest::sha256(b"tool-record"),
2132        )
2133        .unwrap();
2134        NodeInvocationBinding::restore_tool(activation.clone(), head).unwrap()
2135    }
2136
2137    fn bounded(value: Value) -> BoundedJson {
2138        BoundedJson::try_from_value_with_limits(value, JsonLimits::MAXIMUM).unwrap()
2139    }
2140
2141    fn update(activation: &NodeActivation) -> NodeStateUpdate {
2142        NodeStateUpdate::new(
2143            activation.base_checkpoint().graph().state_schema().clone(),
2144            bounded(json!({"approved": true, "amount": 42})),
2145        )
2146        .unwrap()
2147    }
2148
2149    fn route_intent(activation: &NodeActivation) -> PendingNodeResultIntent {
2150        let bindings = NodeInvocationBindings::try_new(
2151            activation,
2152            [tool_binding(activation), model_binding(activation)],
2153        )
2154        .unwrap();
2155        PendingNodeResultIntent::new(
2156            activation.clone(),
2157            NodeStateChange::Update {
2158                update: update(activation),
2159            },
2160            NodeControl::Route {
2161                route_id: RouteId::new("approved").unwrap(),
2162            },
2163            bindings,
2164        )
2165        .unwrap()
2166    }
2167
2168    #[test]
2169    fn route_ids_enforce_the_closed_wire_grammar() {
2170        for valid in ["approved", "route.v2", "retry_path", "A-1"] {
2171            let route = RouteId::new(valid).unwrap();
2172            assert_eq!(route.as_str(), valid);
2173            assert_eq!(from_value::<RouteId>(json!(valid)).unwrap(), route);
2174        }
2175        for invalid in ["", ".", "..", "-route", "route/path", "route space"] {
2176            assert!(RouteId::new(invalid).is_err(), "accepted {invalid:?}");
2177        }
2178        assert!(RouteId::new("r".repeat(RouteId::MAX_LEN + 1)).is_err());
2179        assert!(from_value::<RouteId>(json!(42)).is_err());
2180    }
2181
2182    #[test]
2183    fn schema_pinned_payloads_are_integrity_bound_and_debug_redacted() {
2184        let activation = node_activation("authorize");
2185        let update = update(&activation);
2186        let wire = to_value(&update).unwrap();
2187        assert_eq!(from_value::<NodeStateUpdate>(wire.clone()).unwrap(), update);
2188
2189        let mut tampered = wire;
2190        tampered["data"]["approved"] = json!(false);
2191        assert!(from_value::<NodeStateUpdate>(tampered).is_err());
2192
2193        let secret = "do-not-print-node-payload";
2194        let terminal = NodeTerminalOutput::new(
2195            activation.base_checkpoint().graph().state_schema().clone(),
2196            bounded(json!({"secret": secret})),
2197        )
2198        .unwrap();
2199        assert!(!format!("{terminal:?}").contains(secret));
2200        let mut terminal_wire = to_value(&terminal).unwrap();
2201        terminal_wire["digest"] = json!(Digest::sha256(b"wrong"));
2202        assert!(from_value::<NodeTerminalOutput>(terminal_wire).is_err());
2203    }
2204
2205    #[test]
2206    fn invocation_bindings_are_terminal_activation_bound_unique_and_canonical() {
2207        let activation = node_activation("authorize");
2208        let tool = tool_binding(&activation);
2209        let model = model_binding(&activation);
2210        let bindings =
2211            NodeInvocationBindings::try_new(&activation, [tool.clone(), model.clone()]).unwrap();
2212        assert_eq!(bindings.len(), 2);
2213        assert_eq!(
2214            bindings
2215                .iter()
2216                .map(NodeInvocationBinding::kind)
2217                .collect::<Vec<_>>(),
2218            vec![
2219                NodeInvocationBindingKind::Model,
2220                NodeInvocationBindingKind::Tool
2221            ]
2222        );
2223        assert_eq!(
2224            from_value::<NodeInvocationBindings>(to_value(&bindings).unwrap()).unwrap(),
2225            bindings
2226        );
2227
2228        assert_eq!(
2229            NodeInvocationBindings::try_new(&activation, [tool.clone(), tool]),
2230            Err(NodeInvocationBindingsError::Duplicate {
2231                kind: NodeInvocationBindingKind::Tool,
2232                invocation_id: invocation_id("d2"),
2233            })
2234        );
2235
2236        let other = node_activation("another-node");
2237        assert_eq!(
2238            NodeInvocationBindings::try_new(&other, [model]),
2239            Err(NodeInvocationBindingsError::ActivationMismatch)
2240        );
2241
2242        let executing = ModelInvocationHead::new(
2243            activation.tenant_id().clone(),
2244            activation.run_id(),
2245            invocation_id("d3"),
2246            ModelInvocationRevision::new(1).unwrap(),
2247            ModelInvocationStatus::Executing,
2248            Some(attempt_id("a3")),
2249            journal(&activation, 2),
2250            Digest::sha256(b"executing"),
2251        )
2252        .unwrap();
2253        assert_eq!(
2254            NodeInvocationBinding::restore_model(activation, executing),
2255            Err(NodeInvocationBindingError::ModelNotConsumable {
2256                actual: ModelInvocationStatus::Executing,
2257            })
2258        );
2259    }
2260
2261    #[test]
2262    fn invocation_bindings_accept_known_model_failures_but_reject_unfinished_outcomes() {
2263        let activation = node_activation("call-model");
2264        let failed = ModelInvocationHead::new(
2265            activation.tenant_id().clone(),
2266            activation.run_id(),
2267            invocation_id("d4"),
2268            ModelInvocationRevision::new(2).unwrap(),
2269            ModelInvocationStatus::Failed,
2270            Some(attempt_id("a4")),
2271            journal(&activation, 2),
2272            Digest::sha256(b"known-model-failure"),
2273        )
2274        .unwrap();
2275        assert!(NodeInvocationBinding::restore_model(activation.clone(), failed).is_ok());
2276
2277        for status in [
2278            ModelInvocationStatus::Prepared,
2279            ModelInvocationStatus::Executing,
2280        ] {
2281            let attempt_id = if status == ModelInvocationStatus::Prepared {
2282                None
2283            } else {
2284                Some(AttemptId::generate())
2285            };
2286            let revision = if status == ModelInvocationStatus::Prepared {
2287                ModelInvocationRevision::INITIAL
2288            } else {
2289                ModelInvocationRevision::new(1).unwrap()
2290            };
2291            let head = ModelInvocationHead::new(
2292                activation.tenant_id().clone(),
2293                activation.run_id(),
2294                InvocationId::generate(),
2295                revision,
2296                status,
2297                attempt_id,
2298                journal(&activation, 3),
2299                Digest::sha256(b"unfinished-model"),
2300            )
2301            .unwrap();
2302            assert_eq!(
2303                NodeInvocationBinding::restore_model(activation.clone(), head),
2304                Err(NodeInvocationBindingError::ModelNotConsumable { actual: status })
2305            );
2306        }
2307    }
2308
2309    #[test]
2310    fn invocation_bindings_accept_known_tool_failures_but_reject_uncertain_outcomes() {
2311        let activation = node_activation("execute-tool");
2312        let failed = ToolInvocationHead::new(
2313            activation.tenant_id().clone(),
2314            activation.run_id(),
2315            invocation_id("d4"),
2316            ToolInvocationRevision::new(2).unwrap(),
2317            ToolInvocationStatus::Failed,
2318            Some(attempt_id("a4")),
2319            journal(&activation, 2),
2320            Digest::sha256(b"known-tool-failure"),
2321        )
2322        .unwrap();
2323        assert!(NodeInvocationBinding::restore_tool(activation.clone(), failed).is_ok());
2324
2325        for status in [
2326            ToolInvocationStatus::Prepared,
2327            ToolInvocationStatus::Executing,
2328            ToolInvocationStatus::Unknown,
2329        ] {
2330            let attempt_id = if status == ToolInvocationStatus::Prepared {
2331                None
2332            } else {
2333                Some(AttemptId::generate())
2334            };
2335            let revision = if status == ToolInvocationStatus::Prepared {
2336                ToolInvocationRevision::INITIAL
2337            } else {
2338                ToolInvocationRevision::new(2).unwrap()
2339            };
2340            let head = ToolInvocationHead::new(
2341                activation.tenant_id().clone(),
2342                activation.run_id(),
2343                InvocationId::generate(),
2344                revision,
2345                status,
2346                attempt_id,
2347                journal(&activation, 3),
2348                Digest::sha256(format!("{status:?}").as_bytes()),
2349            )
2350            .unwrap();
2351            assert_eq!(
2352                NodeInvocationBinding::restore_tool(activation.clone(), head),
2353                Err(NodeInvocationBindingError::ToolNotConsumable { actual: status })
2354            );
2355        }
2356    }
2357
2358    #[test]
2359    fn node_wait_batches_are_bounded_identity_unique_and_closed() {
2360        let due_at = "2099-01-01T00:00:00.000000Z".parse().unwrap();
2361        assert_eq!(NodeWaits::try_new([]), Err(NodeWaitsError::Empty));
2362
2363        let timer_id = TimerId::generate();
2364        let timer = NodeWait::timer(timer_id, RunTimerKind::Sleep, due_at);
2365        assert_eq!(
2366            NodeWaits::try_new([timer.clone(), timer]),
2367            Err(NodeWaitsError::DuplicateIdentity)
2368        );
2369
2370        let oversized = (0..=NodeWaits::MAX_LEN)
2371            .map(|_| NodeWait::timer(TimerId::generate(), RunTimerKind::Sleep, due_at));
2372        assert_eq!(
2373            NodeWaits::try_new(oversized),
2374            Err(NodeWaitsError::TooMany {
2375                maximum: NodeWaits::MAX_LEN,
2376                actual: NodeWaits::MAX_LEN + 1,
2377            })
2378        );
2379
2380        let waits = NodeWaits::try_new([NodeWait::timer(
2381            timer_id,
2382            RunTimerKind::RetryBackoff,
2383            due_at,
2384        )])
2385        .unwrap();
2386        let wire = to_value(&waits).unwrap();
2387        assert_eq!(from_value::<NodeWaits>(wire.clone()).unwrap(), waits);
2388        let mut crossed = wire;
2389        crossed[0]["registered_at"] = json!("2098-01-01T00:00:00.000000Z");
2390        assert!(from_value::<NodeWaits>(crossed).is_err());
2391
2392        let schema = to_value(schemars::schema_for!(NodeWaits)).unwrap();
2393        assert_eq!(schema["minItems"], 1);
2394        assert_eq!(schema["maxItems"], NodeWaits::MAX_LEN);
2395        assert_eq!(schema["uniqueItems"], true);
2396    }
2397
2398    #[test]
2399    fn interrupt_node_wait_preserves_policy_and_uses_the_lifecycle_event_clock() {
2400        let activation = node_activation("approval");
2401        let secret = "approve-production-deployment";
2402        let request_payload = JournalPayload::new(
2403            SchemaReference::new(
2404                "https://stknot.com/schemas/tests/node-wait-request/1.0.0"
2405                    .parse()
2406                    .unwrap(),
2407                crate::Version::new(1, 0, 0),
2408                Digest::sha256(b"node wait request schema"),
2409            ),
2410            crate::JournalEventKind::new("node-wait-request").unwrap(),
2411            bounded(json!({"request": secret})),
2412        )
2413        .unwrap();
2414        let event_id = EventId::generate();
2415        let interrupt_id = crate::InterruptId::generate();
2416        let action_digest = Digest::sha256(b"approve deployment action");
2417        let registered_at = Timestamp::from_unix_micros(
2418            activation
2419                .base_checkpoint()
2420                .journal_head()
2421                .recorded_at()
2422                .unix_micros()
2423                + 5_000_000,
2424        )
2425        .unwrap();
2426        let expires_at =
2427            Timestamp::from_unix_micros(registered_at.unix_micros() + 60_000_000).unwrap();
2428        let wait = NodeWait::interrupt(
2429            interrupt_id,
2430            crate::RunInterruptKind::Approval,
2431            request_payload,
2432            action_digest,
2433            None,
2434            ScopeSet::empty(),
2435            Some(expires_at),
2436        );
2437        assert!(!format!("{wait:?}").contains(secret));
2438
2439        let mut registrations = NodeWaits::try_new([wait])
2440            .unwrap()
2441            .registration_intents(activation.tenant_id(), activation.run_id(), event_id)
2442            .unwrap();
2443        let registration = registrations.pop().unwrap();
2444        let WaitRegistrationIntent::Interrupt { request } = &registration else {
2445            panic!("expected interrupt registration")
2446        };
2447        assert_eq!(request.interrupt_id(), interrupt_id);
2448        assert_eq!(request.request_event_id(), event_id);
2449        assert_eq!(request.action_digest(), action_digest);
2450        assert_eq!(request.expires_at(), Some(expires_at));
2451
2452        let journal = JournalHead::new(
2453            activation.tenant_id().clone(),
2454            activation.run_id(),
2455            JournalSequence::new(10).unwrap(),
2456            event_id,
2457            registered_at,
2458            Digest::sha256(b"node wait lifecycle event"),
2459        );
2460        let crate::DurableWait::Interrupt { request } = registration.commit(journal).unwrap()
2461        else {
2462            panic!("expected materialized interrupt")
2463        };
2464        assert_eq!(request.marker().requested_at(), registered_at);
2465        assert_eq!(request.marker().expires_at(), Some(expires_at));
2466    }
2467
2468    #[test]
2469    fn pending_result_separates_semantic_idempotency_from_physical_provenance() {
2470        let activation = node_activation("authorize");
2471        let intent = route_intent(&activation);
2472        let first = PendingNodeResult::commit(
2473            intent.clone(),
2474            fence(&activation, "b1", 1),
2475            journal(&activation, 4),
2476        )
2477        .unwrap();
2478        let replacement = PendingNodeResult::commit(
2479            intent.clone(),
2480            fence(&activation, "b2", 2),
2481            journal(&activation, 5),
2482        )
2483        .unwrap();
2484
2485        assert_eq!(
2486            first.intent().intent_digest(),
2487            replacement.intent().intent_digest()
2488        );
2489        assert_ne!(first.digest(), replacement.digest());
2490        assert_eq!(
2491            from_value::<PendingNodeResult>(to_value(&first).unwrap()).unwrap(),
2492            first
2493        );
2494        assert_eq!(
2495            from_value::<PendingNodeResultHead>(to_value(first.head()).unwrap()).unwrap(),
2496            first.head()
2497        );
2498
2499        let mut changed_route = to_value(&intent).unwrap();
2500        changed_route["control"]["route_id"] = json!("rejected");
2501        assert!(from_value::<PendingNodeResultIntent>(changed_route).is_err());
2502
2503        let mut changed_fence = to_value(&first).unwrap();
2504        changed_fence["fence"]["epoch"] = json!("2");
2505        assert!(from_value::<PendingNodeResult>(changed_fence).is_err());
2506
2507        let mut extra = to_value(&first).unwrap();
2508        extra["unsafe_extension"] = json!(true);
2509        assert!(from_value::<PendingNodeResult>(extra).is_err());
2510    }
2511
2512    #[test]
2513    fn result_anchor_must_follow_bindings_and_waits_materialize_at_lifecycle_event() {
2514        let activation = node_activation("authorize");
2515        let intent = route_intent(&activation);
2516        assert_eq!(
2517            PendingNodeResult::commit(
2518                intent.clone(),
2519                fence(&activation, "b1", 1),
2520                journal(&activation, 3),
2521            ),
2522            Err(PendingNodeResultError::JournalNotAfterBinding)
2523        );
2524
2525        let timer_id = "01912345-6789-7abc-8def-0123456789e1"
2526            .parse::<TimerId>()
2527            .unwrap();
2528        let due_at = Timestamp::from_unix_micros(
2529            activation
2530                .base_checkpoint()
2531                .journal_head()
2532                .recorded_at()
2533                .unix_micros()
2534                + 5_000_000,
2535        )
2536        .unwrap();
2537        let waits =
2538            NodeWaits::try_new([NodeWait::timer(timer_id, RunTimerKind::Sleep, due_at)]).unwrap();
2539        let lifecycle_event_id: EventId = "01912345-6789-7abc-8def-0123456789f1".parse().unwrap();
2540        let registrations = waits
2541            .registration_intents(
2542                activation.tenant_id(),
2543                activation.run_id(),
2544                lifecycle_event_id,
2545            )
2546            .unwrap();
2547        assert_eq!(registrations.len(), 1);
2548        let WaitRegistrationIntent::Timer { timer } = &registrations[0] else {
2549            panic!("expected timer registration");
2550        };
2551        assert_eq!(timer.timer_id(), timer_id);
2552        assert_eq!(timer.registration_event_id(), lifecycle_event_id);
2553        assert_eq!(timer.due_at(), due_at);
2554
2555        let intent = PendingNodeResultIntent::new(
2556            activation.clone(),
2557            NodeStateChange::Unchanged,
2558            NodeControl::Wait { waits },
2559            NodeInvocationBindings::empty(),
2560        )
2561        .unwrap();
2562        PendingNodeResult::commit(intent, fence(&activation, "b1", 1), journal(&activation, 2))
2563            .unwrap();
2564    }
2565
2566    #[test]
2567    fn pending_result_public_schema_is_closed_and_bounded() {
2568        let schema = to_value(schemars::schema_for!(PendingNodeResult)).unwrap();
2569        assert_eq!(schema["additionalProperties"], false);
2570
2571        let bindings_schema = to_value(schemars::schema_for!(NodeInvocationBindings)).unwrap();
2572        assert_eq!(bindings_schema["maxItems"], NodeInvocationBindings::MAX_LEN);
2573        assert_eq!(bindings_schema["uniqueItems"], true);
2574    }
2575}