Skip to main content

causa_kernel/ports/
control.rs

1//! Control planes — the cooperative-cancellation kit handed to port
2//! implementors. `AttemptControl` rides on `ModelGateway::invoke`,
3//! `CallControl` on `Tool::execute`; both carry the turn-shared
4//! `CancellationToken` plus a deadline chain (turn → attempt → call). The
5//! turn-level bundling (`RunControl`) is reference-driver vocabulary and
6//! lives in
7//! `causa_runtime::control`, not here: no port signature consumes it.
8
9use std::time::{Duration, Instant};
10use tokio_util::sync::CancellationToken;
11
12/// Fold a parent deadline and a timeout into the effective deadline: the
13/// earlier of the two, where "no parent"/"no timeout" each leave the other
14/// side in force. External drivers narrow turn deadlines into attempt
15/// deadlines through this fold.
16pub fn effective_deadline(parent: Option<Instant>, timeout: Option<Duration>) -> Option<Instant> {
17    let from_timeout = timeout.map(|t| Instant::now() + t);
18    match (parent, from_timeout) {
19        (Some(a), Some(b)) => Some(a.min(b)),
20        (Some(a), None) => Some(a),
21        (None, Some(b)) => Some(b),
22        (None, None) => None,
23    }
24}
25
26/// One model attempt's control plane: the turn-shared [`CancellationToken`]
27/// plus the effective attempt deadline (turn deadline folded with the
28/// attempt timeout).
29#[derive(Debug, Clone)]
30pub struct AttemptControl {
31    cancellation: CancellationToken,
32    deadline: Option<Instant>,
33}
34impl AttemptControl {
35    /// Builds an attempt control. External drivers construct these directly
36    /// — e.g. through the `causa_runtime::control::RunControl::for_attempt`
37    /// chain or from a bare token.
38    pub fn new(cancellation: CancellationToken, deadline: Option<Instant>) -> Self {
39        Self {
40            cancellation,
41            deadline,
42        }
43    }
44    /// Whether the turn's cancellation has fired.
45    pub fn is_cancelled(&self) -> bool {
46        self.cancellation.is_cancelled()
47    }
48    /// The effective attempt deadline, if any.
49    pub fn deadline(&self) -> Option<Instant> {
50        self.deadline
51    }
52    /// The turn-shared primitive — race it against in-flight provider work
53    /// (`select!`) instead of polling.
54    pub fn cancellation_token(&self) -> &CancellationToken {
55        &self.cancellation
56    }
57    /// Narrows this attempt control into a [`CallControl`] for one tool
58    /// call, folding `call_timeout` into the deadline chain.
59    pub fn for_call(&self, call_timeout: Option<Duration>) -> CallControl {
60        CallControl {
61            cancellation: self.cancellation.clone(),
62            deadline: effective_deadline(self.deadline, call_timeout),
63        }
64    }
65}
66
67/// One tool call's control plane: the same turn-shared [`CancellationToken`]
68/// with the deadline narrowed to the call.
69#[derive(Debug, Clone)]
70pub struct CallControl {
71    cancellation: CancellationToken,
72    deadline: Option<Instant>,
73}
74
75/// Why a control check failed.
76#[derive(Debug, Clone, thiserror::Error)]
77pub enum ControlError {
78    /// The turn was cancelled.
79    #[error("cancelled")]
80    Cancelled,
81    /// The effective deadline has passed.
82    #[error("deadline exceeded")]
83    TimedOut,
84}
85impl CallControl {
86    /// Build a `CallControl` from a cancellation token and an optional
87    /// duration-based deadline. Prefer `AttemptControl::for_call`, which
88    /// folds the parent attempt deadline in; this constructor is for tests
89    /// and callers that cannot go through it.
90    pub fn new(cancellation: CancellationToken, call_timeout: Option<Duration>) -> Self {
91        let deadline = call_timeout.map(|d| Instant::now() + d);
92        Self {
93            cancellation,
94            deadline,
95        }
96    }
97
98    /// Whether the turn's cancellation has fired.
99    pub fn is_cancelled(&self) -> bool {
100        self.cancellation.is_cancelled()
101    }
102    /// The effective call deadline, if any.
103    pub fn deadline(&self) -> Option<Instant> {
104        self.deadline
105    }
106    /// The turn-shared primitive — race it against in-flight tool work
107    /// instead of polling.
108    pub fn cancellation_token(&self) -> &CancellationToken {
109        &self.cancellation
110    }
111    /// Sync guard for tool loops: `Err` when the turn is cancelled or the
112    /// effective deadline has passed.
113    pub fn check(&self) -> Result<(), ControlError> {
114        if self.cancellation.is_cancelled() {
115            return Err(ControlError::Cancelled);
116        }
117        if self.deadline.map(|d| Instant::now() >= d).unwrap_or(false) {
118            return Err(ControlError::TimedOut);
119        }
120        Ok(())
121    }
122}