Skip to main content

reef_core/value/
lifecycle.rs

1//! Provider-neutral lifecycle identity and terminal facts.
2
3use std::{
4    error::Error,
5    fmt::{self, Display, Formatter},
6    num::NonZeroU64,
7};
8
9/// Identifies how a started lifecycle scope ended.
10#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
11#[non_exhaustive]
12pub enum Outcome {
13    /// The scope finished its normal success path.
14    Completed,
15    /// The consumer or an explicit run stop ended the scope.
16    Stopped,
17    /// Parent cancellation or a deadline ended the scope.
18    Cancelled,
19    /// An execution or contract error ended the scope.
20    ///
21    /// This variant says only *that* something failed. For a Run, the reason is
22    /// one call away and is worth reaching for before reporting anything:
23    /// [`Terminal::failure_kind`](crate::runtime::run::Terminal::failure_kind)
24    /// classifies it and [`Terminal::failure`](crate::runtime::run::Terminal::failure)
25    /// returns the error, whose
26    /// [`source`](std::error::Error::source) chain reaches the provider or
27    /// hook error underneath.
28    Failed,
29}
30
31/// Explains why a lifecycle coordinate could not be constructed.
32#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
33#[non_exhaustive]
34pub enum CoordError {
35    /// The containing session identity was empty.
36    EmptySessionId,
37    /// The containing run identity was empty.
38    EmptyRunId,
39    /// A per-turn step number exceeded its run-wide step number.
40    #[non_exhaustive]
41    StepExceedsStepInRun {
42        /// The one-based step number within the turn.
43        step: NonZeroU64,
44        /// The one-based step number across the run.
45        step_in_run: NonZeroU64,
46    },
47    /// The model-assigned tool-call identity was empty.
48    EmptyCallId,
49    /// The effective tool name was empty.
50    EmptyToolName,
51}
52
53impl Display for CoordError {
54    fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
55        match self {
56            Self::EmptySessionId => formatter.write_str("session ID must not be empty"),
57            Self::EmptyRunId => formatter.write_str("run ID must not be empty"),
58            Self::StepExceedsStepInRun { step, step_in_run } => write!(
59                formatter,
60                "step {step} must not exceed run-wide step {step_in_run}"
61            ),
62            Self::EmptyCallId => formatter.write_str("tool-call ID must not be empty"),
63            Self::EmptyToolName => formatter.write_str("tool name must not be empty"),
64        }
65    }
66}
67
68impl Error for CoordError {}
69
70/// The complete, internally consistent numeric location of a step.
71///
72/// This reusable value carries the required parent turn and both views of the
73/// step number. Its private fields prevent external code from forging an
74/// inconsistent location.
75///
76/// ```compile_fail
77/// use std::num::NonZeroU64;
78/// use reef_core::value::lifecycle;
79/// let one = NonZeroU64::new(1).unwrap();
80/// let _forged = lifecycle::StepIndex { turn: one, step: one, step_in_run: one };
81/// ```
82#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
83pub struct StepIndex {
84    turn: NonZeroU64,
85    step: NonZeroU64,
86    step_in_run: NonZeroU64,
87}
88
89impl StepIndex {
90    /// Creates a step location below `turn`.
91    ///
92    /// # Errors
93    ///
94    /// Returns [`CoordError::StepExceedsStepInRun`] when the per-turn step
95    /// number exceeds the run-wide step number.
96    pub fn new(
97        turn: NonZeroU64,
98        step: NonZeroU64,
99        step_in_run: NonZeroU64,
100    ) -> Result<Self, CoordError> {
101        if step > step_in_run {
102            return Err(CoordError::StepExceedsStepInRun { step, step_in_run });
103        }
104        Ok(Self {
105            turn,
106            step,
107            step_in_run,
108        })
109    }
110
111    /// Returns the one-based parent turn number.
112    #[must_use]
113    pub const fn turn(self) -> NonZeroU64 {
114        self.turn
115    }
116
117    /// Returns the one-based step number within the turn.
118    #[must_use]
119    pub const fn step_in_turn(self) -> NonZeroU64 {
120        self.step
121    }
122
123    /// Returns the one-based step number across the run.
124    #[must_use]
125    pub const fn step_in_run(self) -> NonZeroU64 {
126        self.step_in_run
127    }
128}
129
130#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
131struct GenerationPosition {
132    step: StepIndex,
133    generation: NonZeroU64,
134}
135
136#[derive(Clone, Debug, Eq, Hash, PartialEq)]
137struct ToolCallPosition {
138    generation: GenerationPosition,
139    call_id: String,
140    tool_name: String,
141}
142
143#[derive(Clone, Debug, Eq, Hash, PartialEq)]
144enum Layer {
145    Run,
146    Turn(NonZeroU64),
147    Step(StepIndex),
148    Generation(GenerationPosition),
149    ToolCall(ToolCallPosition),
150}
151
152/// Locates one valid point in a run's execution hierarchy.
153///
154/// Each constructor names the complete hierarchy for its layer. Layer numbers use
155/// [`NonZeroU64`], and a [`StepIndex`] guarantees that a step's run-wide number
156/// cannot precede its per-turn number. A tool call is always nested below a real
157/// model generation.
158///
159/// ```
160/// use std::num::NonZeroU64;
161/// use reef_core::value::lifecycle;
162/// let one = NonZeroU64::new(1).unwrap();
163/// let step = lifecycle::StepIndex::new(one, one, one).unwrap();
164/// let coord = lifecycle::Coord::at_tool_call(
165///     "session-2".into(), "run-7".into(), step, one,
166///     "call-1".into(), "grep".into(),
167/// ).unwrap();
168/// assert_eq!(coord.to_string(), "run-7/turn-1/step-1/gen-1/call-call-1");
169/// ```
170///
171/// Zero cannot be supplied as a layer number.
172///
173/// ```compile_fail
174/// use reef_core::value::lifecycle;
175/// let _ = lifecycle::Coord::at_turn("session".into(), "run".into(), 0);
176/// ```
177///
178/// The former unchecked builder surface is intentionally unavailable.
179///
180/// ```compile_fail
181/// use reef_core::value::lifecycle;
182/// let run = lifecycle::Coord::at_run("session".into(), "run".into()).unwrap();
183/// let _ = run.with_generation(1);
184/// ```
185#[derive(Clone, Debug, Eq, Hash, PartialEq)]
186pub struct Coord {
187    session_id: String,
188    run_id: String,
189    layer: Layer,
190}
191
192impl Coord {
193    /// Creates a coordinate at a run boundary, outside all nested layers.
194    ///
195    /// # Errors
196    ///
197    /// Returns [`CoordError::EmptySessionId`] or [`CoordError::EmptyRunId`] when
198    /// the corresponding identity is empty.
199    pub fn at_run(session_id: String, run_id: String) -> Result<Self, CoordError> {
200        Self::from_parts(session_id, run_id, Layer::Run)
201    }
202
203    /// Creates a coordinate in a turn.
204    ///
205    /// # Errors
206    ///
207    /// Returns an error when a containing identity is empty.
208    pub fn at_turn(
209        session_id: String,
210        run_id: String,
211        turn: NonZeroU64,
212    ) -> Result<Self, CoordError> {
213        Self::from_parts(session_id, run_id, Layer::Turn(turn))
214    }
215
216    /// Creates a coordinate at `step`.
217    ///
218    /// # Errors
219    ///
220    /// Returns an error when a containing identity is empty.
221    pub fn at_step(
222        session_id: String,
223        run_id: String,
224        step: StepIndex,
225    ) -> Result<Self, CoordError> {
226        Self::from_parts(session_id, run_id, Layer::Step(step))
227    }
228
229    /// Creates a coordinate in a real model generation below `step`.
230    ///
231    /// # Errors
232    ///
233    /// Returns an error when a containing identity is empty.
234    pub fn at_generation(
235        session_id: String,
236        run_id: String,
237        step: StepIndex,
238        generation: NonZeroU64,
239    ) -> Result<Self, CoordError> {
240        let position = GenerationPosition { step, generation };
241        Self::from_parts(session_id, run_id, Layer::Generation(position))
242    }
243
244    /// Creates a coordinate in a tool call below a real model generation.
245    ///
246    /// # Errors
247    ///
248    /// Returns an error when a containing identity, call identity, or tool name
249    /// is empty.
250    pub fn at_tool_call(
251        session_id: String,
252        run_id: String,
253        step: StepIndex,
254        generation: NonZeroU64,
255        call_id: String,
256        tool_name: String,
257    ) -> Result<Self, CoordError> {
258        if call_id.is_empty() {
259            return Err(CoordError::EmptyCallId);
260        }
261        if tool_name.is_empty() {
262            return Err(CoordError::EmptyToolName);
263        }
264        let position = ToolCallPosition {
265            generation: GenerationPosition { step, generation },
266            call_id,
267            tool_name,
268        };
269        Self::from_parts(session_id, run_id, Layer::ToolCall(position))
270    }
271
272    fn from_parts(session_id: String, run_id: String, layer: Layer) -> Result<Self, CoordError> {
273        if session_id.is_empty() {
274            return Err(CoordError::EmptySessionId);
275        }
276        if run_id.is_empty() {
277            return Err(CoordError::EmptyRunId);
278        }
279        Ok(Self {
280            session_id,
281            run_id,
282            layer,
283        })
284    }
285
286    /// Returns the containing session identity.
287    #[must_use]
288    pub fn session_id(&self) -> &str {
289        &self.session_id
290    }
291
292    /// Returns the containing run identity.
293    #[must_use]
294    pub fn run_id(&self) -> &str {
295        &self.run_id
296    }
297
298    /// Returns the turn number, or zero at the run boundary.
299    #[must_use]
300    pub const fn turn(&self) -> u64 {
301        match &self.layer {
302            Layer::Run => 0,
303            Layer::Turn(turn) => turn.get(),
304            Layer::Step(step) => step.turn.get(),
305            Layer::Generation(generation) => generation.step.turn.get(),
306            Layer::ToolCall(tool_call) => tool_call.generation.step.turn.get(),
307        }
308    }
309
310    /// Returns the step number within the turn, or zero outside a step.
311    #[must_use]
312    pub const fn step_in_turn(&self) -> u64 {
313        match &self.layer {
314            Layer::Run | Layer::Turn(_) => 0,
315            Layer::Step(step) => step.step.get(),
316            Layer::Generation(generation) => generation.step.step.get(),
317            Layer::ToolCall(tool_call) => tool_call.generation.step.step.get(),
318        }
319    }
320
321    /// Returns the step number across the run, or zero outside a step.
322    #[must_use]
323    pub const fn step_in_run(&self) -> u64 {
324        match &self.layer {
325            Layer::Run | Layer::Turn(_) => 0,
326            Layer::Step(step) => step.step_in_run.get(),
327            Layer::Generation(generation) => generation.step.step_in_run.get(),
328            Layer::ToolCall(tool_call) => tool_call.generation.step.step_in_run.get(),
329        }
330    }
331
332    /// Returns the generation number, or zero outside a generation.
333    #[must_use]
334    pub const fn generation(&self) -> u64 {
335        match &self.layer {
336            Layer::Run | Layer::Turn(_) | Layer::Step(_) => 0,
337            Layer::Generation(generation) => generation.generation.get(),
338            Layer::ToolCall(tool_call) => tool_call.generation.generation.get(),
339        }
340    }
341
342    /// Returns the model-assigned tool-call identity, or an empty string outside a call.
343    #[must_use]
344    pub fn call_id(&self) -> &str {
345        match &self.layer {
346            Layer::ToolCall(tool_call) => &tool_call.call_id,
347            _ => "",
348        }
349    }
350
351    /// Returns the effective tool name, or an empty string outside a call.
352    #[must_use]
353    pub fn tool_name(&self) -> &str {
354        match &self.layer {
355            Layer::ToolCall(tool_call) => &tool_call.tool_name,
356            _ => "",
357        }
358    }
359}
360
361impl Display for Coord {
362    fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
363        formatter.write_str(&self.run_id)?;
364        if self.turn() > 0 {
365            write!(formatter, "/turn-{}", self.turn())?;
366        }
367        if self.step_in_turn() > 0 {
368            write!(formatter, "/step-{}", self.step_in_turn())?;
369        }
370        if self.generation() > 0 {
371            write!(formatter, "/gen-{}", self.generation())?;
372        }
373        if !self.call_id().is_empty() {
374            write!(formatter, "/call-{}", self.call_id())?;
375        }
376        Ok(())
377    }
378}
379
380/// The serialized form of [`Outcome`] and [`Coord`] (ADR-019 D5).
381///
382/// A coordinate travels as the eight values its accessors return, with the same
383/// absence encoding they use: `0` for a layer number outside its layer, `""` for
384/// a call identity or tool name outside a call. The private layer enum is
385/// deliberately not the wire shape. A reader of the public API sees the
386/// accessors, so the wire shows the same thing, and a future dimension arrives as
387/// one more accessor and therefore as one more field rather than as a new variant.
388///
389/// Reading one dispatches back to the `at_*` constructors, so a coordinate that
390/// no constructor could have produced — a step without a run-wide step, a tool
391/// name without a call identity, a generation below no step — is refused by name
392/// rather than rebuilt.
393///
394/// This leaves [`Display`] untouched: that is the run-relative path and omits
395/// `session_id`, while this is the complete structural projection and includes
396/// it. Two frozen contracts, neither derived from the other.
397#[cfg(feature = "serde")]
398mod serde_impl {
399    use std::fmt::{self, Formatter};
400    use std::num::NonZeroU64;
401
402    use serde_core::de::{
403        Deserialize, Deserializer, EnumAccess, Error as DeError, MapAccess, SeqAccess,
404        VariantAccess, Visitor,
405    };
406    use serde_core::ser::{Serialize, SerializeStruct, Serializer};
407
408    use super::{Coord, Outcome, StepIndex};
409    use crate::wire::{self, IdentifierSeed};
410
411    const OUTCOME_NAME: &str = "Outcome";
412    const OUTCOME_VARIANTS: &[&str] = &["completed", "stopped", "canceled", "failed"];
413    const COORD_FIELDS: &[&str] = &[
414        "session_id",
415        "run_id",
416        "turn",
417        "step",
418        "step_in_run",
419        "generation",
420        "call_id",
421        "tool_name",
422    ];
423
424    /// Names the refusal a caller sees when the eight numbers do not describe a
425    /// point any constructor can reach.
426    struct InvalidLayer;
427
428    impl fmt::Display for InvalidLayer {
429        fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
430            formatter.write_str(
431                "coordinate layer values do not describe a run, turn, step, generation or tool call",
432            )
433        }
434    }
435
436    // -- Outcome -------------------------------------------------------------
437
438    impl Serialize for Outcome {
439        fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
440        where
441            S: Serializer,
442        {
443            let (index, tag) = match self {
444                Self::Completed => (0, "completed"),
445                Self::Stopped => (1, "stopped"),
446                Self::Cancelled => (2, "canceled"),
447                Self::Failed => (3, "failed"),
448            };
449            serializer.serialize_unit_variant(OUTCOME_NAME, index, tag)
450        }
451    }
452
453    impl<'de> Deserialize<'de> for Outcome {
454        fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
455        where
456            D: Deserializer<'de>,
457        {
458            deserializer.deserialize_enum(OUTCOME_NAME, OUTCOME_VARIANTS, OutcomeVisitor)
459        }
460    }
461
462    struct OutcomeVisitor;
463
464    impl<'de> Visitor<'de> for OutcomeVisitor {
465        type Value = Outcome;
466
467        fn expecting(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
468            formatter.write_str("a lifecycle outcome")
469        }
470
471        fn visit_enum<A>(self, data: A) -> Result<Self::Value, A::Error>
472        where
473            A: EnumAccess<'de>,
474        {
475            let (tag, variant) = data.variant_seed(IdentifierSeed(OUTCOME_VARIANTS))?;
476            variant.unit_variant()?;
477            match tag.0.as_str() {
478                "completed" => Ok(Outcome::Completed),
479                "stopped" => Ok(Outcome::Stopped),
480                "canceled" => Ok(Outcome::Cancelled),
481                "failed" => Ok(Outcome::Failed),
482                unknown => Err(A::Error::unknown_variant(unknown, OUTCOME_VARIANTS)),
483            }
484        }
485    }
486
487    // -- Coord ---------------------------------------------------------------
488
489    impl Serialize for Coord {
490        fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
491        where
492            S: Serializer,
493        {
494            let mut record = serializer.serialize_struct("Coord", 8)?;
495            record.serialize_field("session_id", self.session_id())?;
496            record.serialize_field("run_id", self.run_id())?;
497            record.serialize_field("turn", &self.turn())?;
498            record.serialize_field("step", &self.step_in_turn())?;
499            record.serialize_field("step_in_run", &self.step_in_run())?;
500            record.serialize_field("generation", &self.generation())?;
501            record.serialize_field("call_id", self.call_id())?;
502            record.serialize_field("tool_name", self.tool_name())?;
503            record.end()
504        }
505    }
506
507    impl<'de> Deserialize<'de> for Coord {
508        fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
509        where
510            D: Deserializer<'de>,
511        {
512            deserializer.deserialize_struct("Coord", COORD_FIELDS, CoordVisitor)
513        }
514    }
515
516    /// The eight flat values a coordinate travels as, before they are checked.
517    struct Flat {
518        session_id: String,
519        run_id: String,
520        turn: u64,
521        step: u64,
522        step_in_run: u64,
523        generation: u64,
524        call_id: String,
525        tool_name: String,
526    }
527
528    impl Flat {
529        /// Dispatches the eight values back to the constructor that owns their
530        /// shape.
531        ///
532        /// Every accepted combination is one arm and everything else is the
533        /// refusal arm. Writing it as a single match over the whole tuple rather
534        /// than as a chain of conditions is what makes "no other combination is
535        /// legal" a property of the code instead of a claim about it.
536        fn build<E>(self) -> Result<Coord, E>
537        where
538            E: DeError,
539        {
540            let Self {
541                session_id,
542                run_id,
543                turn,
544                step,
545                step_in_run,
546                generation,
547                call_id,
548                tool_name,
549            } = self;
550            let built = match (
551                NonZeroU64::new(turn),
552                NonZeroU64::new(step),
553                NonZeroU64::new(step_in_run),
554                NonZeroU64::new(generation),
555                call_id.is_empty(),
556                tool_name.is_empty(),
557            ) {
558                (None, None, None, None, true, true) => Coord::at_run(session_id, run_id),
559                (Some(turn), None, None, None, true, true) => {
560                    Coord::at_turn(session_id, run_id, turn)
561                }
562                (Some(turn), Some(step), Some(step_in_run), None, true, true) => {
563                    StepIndex::new(turn, step, step_in_run)
564                        .and_then(|index| Coord::at_step(session_id, run_id, index))
565                }
566                (Some(turn), Some(step), Some(step_in_run), Some(generation), true, true) => {
567                    StepIndex::new(turn, step, step_in_run).and_then(|index| {
568                        Coord::at_generation(session_id, run_id, index, generation)
569                    })
570                }
571                (Some(turn), Some(step), Some(step_in_run), Some(generation), false, false) => {
572                    StepIndex::new(turn, step, step_in_run).and_then(|index| {
573                        Coord::at_tool_call(
574                            session_id, run_id, index, generation, call_id, tool_name,
575                        )
576                    })
577                }
578                _ => return Err(E::custom(InvalidLayer)),
579            };
580            built.map_err(E::custom)
581        }
582    }
583
584    struct CoordVisitor;
585
586    impl<'de> Visitor<'de> for CoordVisitor {
587        type Value = Coord;
588
589        fn expecting(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
590            formatter.write_str("a lifecycle coordinate")
591        }
592
593        fn visit_seq<A>(self, mut sequence: A) -> Result<Self::Value, A::Error>
594        where
595            A: SeqAccess<'de>,
596        {
597            let session_id = wire::element(&mut sequence, 0)?;
598            let run_id = wire::element(&mut sequence, 1)?;
599            let turn = wire::element(&mut sequence, 2)?;
600            let step = wire::element(&mut sequence, 3)?;
601            let step_in_run = wire::element(&mut sequence, 4)?;
602            let generation = wire::element(&mut sequence, 5)?;
603            let call_id = wire::element(&mut sequence, 6)?;
604            let tool_name = wire::element(&mut sequence, 7)?;
605            wire::end(&mut sequence, 8)?;
606            Flat {
607                session_id,
608                run_id,
609                turn,
610                step,
611                step_in_run,
612                generation,
613                call_id,
614                tool_name,
615            }
616            .build()
617        }
618
619        fn visit_map<A>(self, mut entries: A) -> Result<Self::Value, A::Error>
620        where
621            A: MapAccess<'de>,
622        {
623            let mut session_id = None;
624            let mut run_id = None;
625            let mut turn = None;
626            let mut step = None;
627            let mut step_in_run = None;
628            let mut generation = None;
629            let mut call_id = None;
630            let mut tool_name = None;
631            while let Some(field) = entries.next_key_seed(IdentifierSeed(COORD_FIELDS))? {
632                match field.0.as_str() {
633                    "session_id" => {
634                        wire::accept(&mut session_id, entries.next_value()?, "session_id")?;
635                    }
636                    "run_id" => wire::accept(&mut run_id, entries.next_value()?, "run_id")?,
637                    "turn" => wire::accept(&mut turn, entries.next_value()?, "turn")?,
638                    "step" => wire::accept(&mut step, entries.next_value()?, "step")?,
639                    "step_in_run" => {
640                        wire::accept(&mut step_in_run, entries.next_value()?, "step_in_run")?;
641                    }
642                    "generation" => {
643                        wire::accept(&mut generation, entries.next_value()?, "generation")?;
644                    }
645                    "call_id" => wire::accept(&mut call_id, entries.next_value()?, "call_id")?,
646                    "tool_name" => {
647                        wire::accept(&mut tool_name, entries.next_value()?, "tool_name")?;
648                    }
649                    unknown => return Err(A::Error::unknown_field(unknown, COORD_FIELDS)),
650                }
651            }
652            Flat {
653                session_id: wire::require(session_id, "session_id")?,
654                run_id: wire::require(run_id, "run_id")?,
655                turn: wire::require(turn, "turn")?,
656                step: wire::require(step, "step")?,
657                step_in_run: wire::require(step_in_run, "step_in_run")?,
658                generation: wire::require(generation, "generation")?,
659                call_id: wire::require(call_id, "call_id")?,
660                tool_name: wire::require(tool_name, "tool_name")?,
661            }
662            .build()
663        }
664    }
665}