Skip to main content

causa_kernel/ports/
batch.rs

1//! Controlled tool-batch facts and the processor contract.
2
3use crate::context::block::{MediaRef, TextPayload, ToolCallPayload};
4use crate::context::ids::BlockId;
5use crate::context::ids::{RoundId, TurnId};
6use crate::context::tool_data::{ToolOutput, ToolResultPayload};
7use crate::ports::control::CallControl;
8use crate::ports::tool::ToolCallContext;
9use async_trait::async_trait;
10use std::collections::HashSet;
11
12/// A declaration plus its optional completed result.
13#[derive(Debug)]
14pub struct ToolCallEntry {
15    call: ToolCallContext,
16    result: Option<(BlockId, ToolResultPayload)>,
17}
18
19impl ToolCallEntry {
20    /// Borrows the declaration and effective execution input.
21    pub fn call(&self) -> &crate::ports::tool::ToolCallContext {
22        &self.call
23    }
24
25    /// Mutably borrows the input while this call is still pending.
26    pub fn input_mut(&mut self) -> Option<&mut ToolCallPayload> {
27        self.result.is_none().then_some(&mut self.call.input)
28    }
29
30    /// Borrows the result block ID and result payload when completed.
31    pub fn result(&self) -> Option<(&BlockId, &ToolResultPayload)> {
32        self.result.as_ref().map(|(id, result)| (id, result))
33    }
34
35    /// Mutably borrows output when this call has a result.
36    pub fn output_mut(&mut self) -> Option<&mut ToolOutput> {
37        self.result.as_mut().map(|(_, result)| &mut result.output)
38    }
39
40    /// Mutably borrows result media when this call has a result.
41    pub fn media_mut(&mut self) -> Option<&mut Vec<MediaRef>> {
42        self.result.as_mut().map(|(_, result)| &mut result.media)
43    }
44
45    /// Adds a note to the pending call or completed result as appropriate.
46    pub fn push_note(&mut self, note: TextPayload) {
47        match self.result.as_mut() {
48            Some((_, result)) => result.notes.push(note),
49            None => self.call.result_notes.push(note),
50        }
51    }
52}
53
54/// One tool batch with a completed prefix and pending suffix.
55///
56/// Each result joins the end of the completed prefix as it is resolved, so
57/// the prefix is in resolution order: with concurrent dispatch, the order the
58/// calls completed in, not the order the model declared them in. That order
59/// is what [`ToolBatch::into_results`] returns and what a runner commits. To
60/// keep declaration order instead, sort [`ToolBatch::results_mut`] by
61/// [`ProcessorContext::declaration_order`] in a processor that runs after
62/// dispatch.
63#[derive(Debug)]
64pub struct ToolBatch {
65    entries: Vec<ToolCallEntry>,
66    completed: usize,
67}
68
69impl ToolBatch {
70    /// Creates a batch from declarations in their original order.
71    pub fn new(calls: Vec<ToolCallContext>) -> Result<Self, BatchError> {
72        let mut declarations = HashSet::with_capacity(calls.len());
73        for call in &calls {
74            if !declarations.insert(call.call_block_id) {
75                return Err(BatchError::DuplicateDeclaration(call.call_block_id));
76            }
77        }
78        let batch = Self {
79            entries: calls
80                .into_iter()
81                .map(|call| ToolCallEntry { call, result: None })
82                .collect(),
83            completed: 0,
84        };
85        batch.validate()?;
86        Ok(batch)
87    }
88
89    /// Returns the pending suffix.
90    pub fn calls(&self) -> &[ToolCallEntry] {
91        &self.entries[self.completed..]
92    }
93
94    /// Mutably returns the pending suffix.
95    pub fn calls_mut(&mut self) -> &mut [ToolCallEntry] {
96        &mut self.entries[self.completed..]
97    }
98
99    /// Returns the completed prefix.
100    pub fn results(&self) -> &[ToolCallEntry] {
101        &self.entries[..self.completed]
102    }
103
104    /// Mutably returns the completed prefix for output editing and ordering.
105    pub fn results_mut(&mut self) -> &mut [ToolCallEntry] {
106        &mut self.entries[..self.completed]
107    }
108
109    /// Returns the number of completed entries.
110    pub fn completed_len(&self) -> usize {
111        self.completed
112    }
113
114    /// Returns declaration identities in the batch's current entry order.
115    pub fn declaration_ids(&self) -> Vec<BlockId> {
116        self.entries
117            .iter()
118            .map(|entry| entry.call.call_block_id)
119            .collect()
120    }
121
122    /// Validates the completed-prefix/pending-suffix and identity invariants.
123    pub fn validate(&self) -> Result<(), BatchError> {
124        if self.completed > self.entries.len() {
125            return Err(BatchError::InvalidPartition(format!(
126                "completed count {} exceeds entry count {}",
127                self.completed,
128                self.entries.len()
129            )));
130        }
131        let mut declarations = HashSet::with_capacity(self.entries.len());
132        for entry in &self.entries {
133            let declaration_id = entry.call.call_block_id;
134            if !declarations.insert(declaration_id) {
135                return Err(BatchError::DuplicateDeclaration(declaration_id));
136            }
137        }
138        let mut all_ids = declarations.clone();
139        for (index, entry) in self.entries.iter().enumerate() {
140            let declaration_id = entry.call.call_block_id;
141            match (index < self.completed, &entry.result) {
142                (true, Some((result_id, result))) => {
143                    if result.call_block_id != declaration_id {
144                        return Err(BatchError::MismatchedCall {
145                            expected: declaration_id,
146                            actual: result.call_block_id,
147                        });
148                    }
149                    if !all_ids.insert(*result_id) {
150                        return Err(BatchError::DuplicateResultBlockId(*result_id));
151                    }
152                }
153                (false, None) => {}
154                (true, None) => {
155                    return Err(BatchError::InvalidPartition(format!(
156                        "completed entry {index} has no result"
157                    )));
158                }
159                (false, Some(_)) => {
160                    return Err(BatchError::InvalidPartition(format!(
161                        "pending entry {index} already has a result"
162                    )));
163                }
164            }
165        }
166        Ok(())
167    }
168
169    /// Installs a result at an absolute entry index and advances the prefix.
170    /// A refused result leaves the batch unchanged and is handed back with
171    /// the reason, so a caller can retry or report it without a copy.
172    pub fn resolve_at(
173        &mut self,
174        index: usize,
175        result_block_id: BlockId,
176        mut result: ToolResultPayload,
177    ) -> Result<(), RejectedToolResult> {
178        if let Err(error) = self.check_resolve(index, result_block_id, &result) {
179            return Err(RejectedToolResult { error, result });
180        }
181        let mut notes = std::mem::take(&mut self.entries[index].call.result_notes);
182        notes.append(&mut result.notes);
183        result.notes = notes;
184        self.entries[index].result = Some((result_block_id, result));
185        self.entries.swap(index, self.completed);
186        self.completed += 1;
187        Ok(())
188    }
189
190    fn check_resolve(
191        &self,
192        index: usize,
193        result_block_id: BlockId,
194        result: &ToolResultPayload,
195    ) -> Result<(), BatchError> {
196        self.validate()?;
197        if index < self.completed || index >= self.entries.len() {
198            return Err(BatchError::InvalidIndex {
199                index,
200                completed: self.completed,
201                total: self.entries.len(),
202            });
203        }
204        let expected = self.entries[index].call.call_block_id;
205        if result.call_block_id != expected {
206            return Err(BatchError::MismatchedCall {
207                expected,
208                actual: result.call_block_id,
209            });
210        }
211        if self.entries[index].result.is_some() {
212            return Err(BatchError::InvalidPartition(format!(
213                "pending entry {index} already has a result"
214            )));
215        }
216        if self.entries.iter().any(|entry| {
217            entry.call.call_block_id == result_block_id
218                || entry
219                    .result
220                    .as_ref()
221                    .is_some_and(|(id, _)| *id == result_block_id)
222        }) {
223            return Err(BatchError::DuplicateResultBlockId(result_block_id));
224        }
225        Ok(())
226    }
227
228    /// Validates the invariants and that every entry has a result.
229    pub fn validate_complete(&self) -> Result<(), BatchError> {
230        self.validate()?;
231        if self.completed != self.entries.len() {
232            return Err(BatchError::Incomplete {
233                completed: self.completed,
234                total: self.entries.len(),
235            });
236        }
237        Ok(())
238    }
239
240    /// Consumes a fully completed batch into result blocks in current order.
241    pub fn into_results(self) -> Result<Vec<(BlockId, ToolResultPayload)>, (BatchError, Self)> {
242        if let Err(error) = self.validate_complete() {
243            return Err((error, self));
244        }
245        Ok(self
246            .entries
247            .into_iter()
248            .map(|entry| entry.result.expect("validated complete entry"))
249            .collect())
250    }
251}
252
253/// Context made available to tool batch processors.
254#[non_exhaustive]
255pub struct ProcessorContext<'a> {
256    /// Turn identity for the active tool batch.
257    pub turn_id: &'a TurnId,
258    /// Model round that declared this batch.
259    pub round_id: RoundId,
260    /// Original declaration order, represented by stable block IDs. The batch's
261    /// own entry order changes as results are resolved; this does not.
262    pub declaration_order: &'a [BlockId],
263    /// Cooperative cancellation and deadline control.
264    pub control: &'a CallControl,
265}
266impl<'a> ProcessorContext<'a> {
267    /// The context one processor run sees.
268    pub fn new(
269        turn_id: &'a TurnId,
270        round_id: RoundId,
271        declaration_order: &'a [BlockId],
272        control: &'a CallControl,
273    ) -> Self {
274        Self {
275            turn_id,
276            round_id,
277            declaration_order,
278            control,
279        }
280    }
281}
282
283/// Failure to finish a processing phase. Per-call rejection is a result,
284/// and should be recorded on the batch while returning `Ok(())`.
285#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
286#[non_exhaustive]
287pub enum ProcessorError {
288    /// The processor could not complete its phase.
289    #[error("processor failed: {0}")]
290    Failed(String),
291}
292
293/// A pre- or post-processing phase over one exclusively borrowed tool batch.
294#[async_trait]
295pub trait ToolBatchProcessor: Send + Sync {
296    /// Processes the batch in place; errors leave its current materials with
297    /// the caller and stop the chain.
298    async fn process(
299        &self,
300        batch: &mut ToolBatch,
301        ctx: &ProcessorContext<'_>,
302    ) -> Result<(), ProcessorError>;
303}
304
305/// Invalid batch construction, completion, or partition state.
306#[derive(Debug, thiserror::Error)]
307#[non_exhaustive]
308pub enum BatchError {
309    /// A declaration appears more than once in a batch.
310    #[error("duplicate declaration block id: {0:?}")]
311    DuplicateDeclaration(BlockId),
312    /// The requested absolute index is not in the pending suffix.
313    #[error("index {index} is not pending (completed {completed}, total {total})")]
314    #[non_exhaustive]
315    InvalidIndex {
316        /// Requested entry index.
317        index: usize,
318        /// Number of entries in the completed prefix.
319        completed: usize,
320        /// Total entry count.
321        total: usize,
322    },
323    /// A result references a different declaration than its entry.
324    #[error("result call ID mismatch: expected {expected:?}, got {actual:?}")]
325    #[non_exhaustive]
326    MismatchedCall {
327        /// Declaration identity expected by the entry.
328        expected: BlockId,
329        /// Declaration identity carried by the result.
330        actual: BlockId,
331    },
332    /// A result's own block identity collides within the batch.
333    #[error("duplicate result block ID: {0:?}")]
334    DuplicateResultBlockId(BlockId),
335    /// The completed prefix and pending suffix disagree with entry contents.
336    #[error("invalid batch partition: {0}")]
337    InvalidPartition(String),
338    /// Not all entries have results.
339    #[error("batch is incomplete: {completed} of {total} entries completed")]
340    #[non_exhaustive]
341    Incomplete {
342        /// Number of completed entries.
343        completed: usize,
344        /// Total number of entries.
345        total: usize,
346    },
347}
348
349/// A result [`ToolBatch::resolve_at`] refused, returned with the reason.
350#[derive(Debug, thiserror::Error)]
351#[error("{error}")]
352#[non_exhaustive]
353pub struct RejectedToolResult {
354    /// Why the batch refused the result.
355    pub error: BatchError,
356    /// The refused result, unchanged.
357    pub result: ToolResultPayload,
358}